Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the NSNumber class correctly converting my NSString object to a long long?

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];
like image 410
BeachRunnerFred Avatar asked Sep 01 '10 21:09

BeachRunnerFred


2 Answers

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.

like image 146
unbeli Avatar answered Oct 14 '22 00:10

unbeli


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.

like image 25
Carl Norum Avatar answered Oct 14 '22 00:10

Carl Norum