0

When I use this code to convert a string inside a array to a long long, it fails and prints out "0" because the string starts with "0x".

This is my array: NSArray <NSString *> *offsets = @["0x1003567"];

When I try to log it with this code:

NSLog(@"Offset: %lld", [offsets[0] longLongValue]);

It prints out: "0"

When I remove the "0x" from 0x1003567, it prints out the correct numbers.

However, I do need the "0x" in order to be able to use it.

Is there any way I can make it convert how I would want it?

jscs
  • 63,694
  • 13
  • 151
  • 195

1 Answers1

0

Your string contains a number in hexadecimal. There's no method on NSString that directly interprets its contents as hexadecimal.

You can use NSScanner to do that.

NSScanner *scanner = [NSScanner scannerWithString:offsets[0]];
unsigned long long result;
if ([scanner scanHexLongLong:&result] && scanner.scanLocation == offsets[0].length)
    NSLog(@"Offset: %llu", result);
else
    /* string was not a hexadecimal number; handle failure */;

By the way, this:

When I remove the "0x" from 0x1003567, it prints out the correct numbers.

is not accurate. It interpreted "1003567" as a decimal number (i.e. 1,003,567) and printed that back out. But that's not the value of 0x1003567. The decimal value of 0x1003567 is 16790887 (i.e. 16,790,887). And if the number had contained hex digits above 9 (the letters A-F), it would have stopped interpreting them at that point.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154