Skip to content

Instantly share code, notes, and snippets.

@nsforge
Created February 12, 2014 03:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nsforge/8949790 to your computer and use it in GitHub Desktop.
Save nsforge/8949790 to your computer and use it in GitHub Desktop.
Demonstration of uint64 accuracy bug in NSJSONSerialization
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