objective-cnsstringnsinteger

How can I cast an NSString as a hex representation of NSInteger


Cast is not the right word, but bear with me. I have the following string:

NSString *string = @"01700000";

However, I need to check if it contains a particular bit I'm looking for:

if (bitshift & (1 << 21)) {
    NSLog(@"YES");
} else {
    NSLog(@"NO");
}

Getting the integer value by using [string integerValue] produces unexpected results:

NSInteger bitshift = (1 << 24) | (1 << 22) | (1 << 21) | (1 << 20);
NSString *flags = @"01700000";
NSInteger bitshiftString = [flags integerValue];

// bitshift: 1700000, bitshiftString: 19f0a0
NSLog(@"bitshift: %tx, bitshiftString: %tx", bitshift, bitshiftString);

What would be the most appropriate way to scan this string value into a NSInteger?


Solution

  • Turns out this is deliciously simple:

    unsigned int bitshiftString;
    [[NSScanner scannerWithString:flags] scanHexInt:&bitshiftString];