为什么 NSNumber 类没有正确地将我的 NSString 对象转换为 long long?
我正在尝试将 NSString 对象转换为具有相同数值的 NSNumber 。当我使用此语句创建 NSString 对象时...
NSString *songID = [localNotif.userInfo objectForKey:@"SongID"];
var songID
包含字符串值 @"10359537395704663785"
。当我尝试使用语句将其转换为 NSNumber 对象时...
NSNumber *songIDNumber = [NSNumber numberWithLongLong:[songID longLongValue]];
var songIDNumber
包含错误的 9223372036854775807
值
我做错了什么?还值得注意的是,有时此代码确实可以工作并生成正确的 NSNumber 值,但大多数时候它会失败,如上所示。
预先感谢您的帮助!
更新:天哪,我喜欢这个网站!感谢 unbeli 和 carl,我能够使用更新的代码来修复它,从 NSString 转换为 NSNumber...
unsigned long long ullvalue = strtoull([songID UTF8String], NULL, 0);
NSNumber *songIDNumber = [NSNumber numberWithUnsignedLongLong:ullvalue];
I'm trying to convert an NSString object to an NSNumber with the same numerical value. When I create the NSString object using this statement...
NSString *songID = [localNotif.userInfo objectForKey:@"SongID"];
the var songID
contains the string value @"10359537395704663785"
. and when I attempt to convert it to an NSNumber object using the statement...
NSNumber *songIDNumber = [NSNumber numberWithLongLong:[songID longLongValue]];
the var songIDNumber
contains the wrong value of 9223372036854775807
What am I doing wrong? It might also be worth noting that sometimes this code does work and produce the correct NSNumber value, but most of the time it fails as shown above.
Thanks in advance for your help!
UPDATE: God I love this site! Thanks to unbeli and carl, I was able to fix it using the updated code for converting from the NSString to the NSNumber...
unsigned long long ullvalue = strtoull([songID UTF8String], NULL, 0);
NSNumber *songIDNumber = [NSNumber numberWithUnsignedLongLong:ullvalue];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
longLongValue
在溢出的情况下返回LLONG_MAX
,而LLONG_MAX
正是您得到的,9223372036854775807。您值根本不适合long long
尝试使用 NSDecimalNumber 代替。
longLongValue
returnsLLONG_MAX
in case of overflow, andLLONG_MAX
is exactly what you get, 9223372036854775807. You value simply does not fit inlong long
Try using NSDecimalNumber instead.
9223372036854775807
十进制是0x7FFFFFFFFFFFFFFF
十六进制。您的号码是10359537395704663785
,对于long long
来说太大并且溢出。来自 NSString 文档:9223372036854775807
decimal is0x7FFFFFFFFFFFFFFF
in hex. Your number is10359537395704663785
, which is too large for along long
and overflows. From the NSString documentation: