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

2

5

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];
Lollipop answered 1/9, 2010 at 21:22 Comment(0)
U
4

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.

Updraft answered 1/9, 2010 at 21:26 Comment(0)
G
5

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.

Greece answered 1/9, 2010 at 21:27 Comment(0)
U
4

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.

Updraft answered 1/9, 2010 at 21:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.