Created
February 12, 2014 03:51
-
-
Save nsforge/8949790 to your computer and use it in GitHub Desktop.
Demonstration of uint64 accuracy bug in NSJSONSerialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSString *jsonString = @"{\"myNumber\":1029742590268606522}"; | |
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; | |
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:NULL]; | |
NSLog(@"jsonDict: %@", jsonDict); | |
uint64_t myNumber = [jsonDict[@"myNumber"] unsignedLongLongValue]; | |
NSLog(@"myNumber: %llu", myNumber); | |
/* | |
Output: | |
2014-02-12 14:47:54.850 Untitled 11[94676:507] jsonDict: { | |
myNumber = 1029742590268606522; | |
} | |
2014-02-12 14:47:54.852 Untitled 11[94676:507] myNumber: 1029742590268606464 | |
Explanation: | |
NSJSONSerialization is inappropriately using NSDecimalNumber instead of a standard long long | |
unsigned NSNumber, and NSDecimalNumber has a bug where getting very large integers out of an | |
NSDecimalNumber loses accuracy since it uses .doubleValue as in interim representation | |
(http://stackoverflow.com/a/6713550/86046). | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment