Search code examples
objective-chexdecimalbigdecimal

Working with big numbers in Objective-C?


I need to convert values like 1393443048683555715 to HEX. But, first of all, i cann't display it as decimal using NSLog(), for example.

Ok, it works:

NSLog(@"%qu", 1393443048683555706);

But what about converting to HEX. What type i have to use to store this big value?

NSLog([NSString stringWithFormat: @"%x", 1393443048683555706]);
// result eb854b7a. It's incorrect result!

but i forgot to say that this big number represented as string @"1393443048683555706" (not int)


Solution

  • The "x" format specifier is for 32-bit numbers; you need to use either "qx" or "qX" (depending on whether you want the letter values to be uppercase or not). These are the formatters for unsigned long long values, see:

    https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1

    Next, you should not pass a string as you have done above directly to NSLog - this can cause a crash.

    NSLog(string); // bad!!
    NSLog(@"%@", string); // good
    

    So if your value comes as a string, you'll want to do this:

    NSString *longNumber = @"1393443048683555706";
    NSLog(@"%qx", [longNumber longLongValue]);
    

    If the string value can't be coerced to a number, longLongValue will return 0. I'll leave it to you do handle the error (and bounds) checking - see NSString for details.

    If you want to save the hex value as a string, do this:

    NSString *hexRepresentation = [NSString stringWithFormat:@"%qx", [longNumber longLongValue]];
    

    Again, best to take care for error handling.