Search code examples
objective-cnsscanner

Best way to convert two digit hexadecimal number to integer


I want to convert a two hexadecimal number to an integer but I'm having some difficulty. The format is "#FF" and I want to convert it to 255 or "#00" and convert to 0. However when I try the following:

unsigned alphaColor = 0;
[[NSScanner scannerWithString:alphaString] scanHexInt:&alphaColor];
alphaVal = alphaColor / 255.0;

It seems to not work as alphaColor is nil. Any ideas how I can convert a two digit hexadecimal?


Solution

  • scanHexInt does not accept the #. It optionally allows for a leading 0x or 0x but not #. You need to read the # first.

    NSScanner *scanner = [NSScanner scannerWithString:alphaString];
    unsigned alphaColor = 0;
    if ([scanner scanString:@"#" intoString:nil] && [scanner scanHexInt:&alphaColor]) {
        alphaVal = alphaColor / 255.0;
    }