NSDecimalNumber and large unsigned long long (64-bit) integers

后端 未结 2 611
野趣味
野趣味 2021-02-19 08:11

I\'m handling large 64 bit unsigned integers from a JSON source which are being parsed into NSDecimalNumbers, which is apparently to \"faithfully represent arbitrary-precision n

2条回答
  •  花落未央
    2021-02-19 09:14

    If you still want to extract an unsigned long long value from an NSDecimalNumber, you could use the approach suggested by johne here and do something like the following:

    NSDecimalNumber *testNumber = [NSDecimalNumber decimalNumberWithString:@"18446744073709551615"];
    unsigned long long ullvalue = strtoull([[testNumber stringValue] UTF8String], NULL, 0);
    NSLog(@"Number:%llu", ullvalue);
    

    which produces the proper result of

    Number:18446744073709551615

    I tried to do this using an NSScanner:

    NSScanner *theScanner = [[NSScanner alloc] initWithString:[testNumber stringValue]];
    unsigned long long outputValue;
    
    [theScanner scanLongLong:(long long *)&outputValue];
    [theScanner release];
    

    but unfortunately, it only reads the signed long long values, so the above gives the incorrect value of 9223372036854775807.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题