views:

111

answers:

2

Hello. 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];
+3  A: 

9223372036854775807 decimal is 0x7FFFFFFFFFFFFFFF in hex. Your number is 10359537395704663785, which is too large for a long long and overflows. From the NSString documentation:

Returns LLONG_MAX or LLONG_MIN on overflow.

Carl Norum
+5  A: 

longLongValue returns LLONG_MAX in case of overflow, and LLONG_MAX is exactly what you get, 9223372036854775807. You value simply does not fit in long long

Try using NSDecimalNumber instead.

unbeli