如何将Cocos中的NSString转换为unsigned int? [英] How to convert an NSString to an unsigned int in Cocoa?

查看:629
本文介绍了如何将Cocos中的NSString转换为unsigned int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序得到一个包含 unsigned int NSString 。 NSString没有 [myString unsignedIntegerValue]; 方法。我想能够从字符串中取出值,而不需要修改它,然后将其放在 NSNumber 中。我想这样做:

My application gets handed an NSString containing an unsigned int. NSString doesn't have an [myString unsignedIntegerValue]; method. I'd like to be able to take the value out of the string without mangling it, and then place it inside an NSNumber. I'm trying to do it like so:

NSString     *myUnsignedIntString = [self someMethodReturningAString];
NSInteger    myInteger            = [myUnsignedIntString integerValue];
NSNumber     *myNSNumber          = [NSNumber numberWithInteger:myInteger];

// ...put |myNumber| in an NSDictionary, time passes, pull it out later on...

unsigned int myUnsignedInt        = [myNSNumber unsignedIntValue];

上述是否可能截断大型 unsigned int 因为我不得不将其转换为 NSInteger 第一?或者它看起来好用吗?如果它会切断它的结束,下面(一点kludge我想)一点?

Will the above potentially "cut off" the end of a large unsigned int since I had to convert it to NSInteger first? Or does it look OK to use? If it'll cut off the end of it, how about the following (a bit of a kludge I think)?

NSString     *myUnsignedIntString = [self someMethodReturningAString];
long long    myLongLong           = [myUnsignedIntString longLongValue];
NSNumber     *myNSNumber          = [NSNumber numberWithLongLong:myLongLong];

// ...put |myNumber| in an NSDictionary, time passes, pull it out later on...

unsigned int myUnsignedInt        = [myNSNumber unsignedIntValue];

感谢您提供任何帮助! :)

Thanks for any help you can offer! :)

推荐答案

第一个版本截断,第二个版本应该很好,只要你的数字实际上适合一个unsigned int - see例如 数据类型大小和对齐

不过,您应该使用 NSNumber + numberWithUnsignedInt

The first version truncates and the second should be fine as long as your number actually fits into an unsigned int - see e.g. "Data Type Size and Alignment".
You should however create the NSNumber using +numberWithUnsignedInt.

如果你知道编码是合适的,你也可以简单地使用C库:

If you know that the encoding is suitable, you could also simply go with the C-libraries:

unsigned n;
sscanf([str UTF8String], "%u", &n);

这篇关于如何将Cocos中的NSString转换为unsigned int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆