Search code examples
objective-cparsingcolor-pickerhexcolor-codes

Convert a string like "ff0000" to hexadecimal number in objective c


I need to convert a string input from UI to a hexadecimal number in objective c. The string is an HTML color code like "ff0000" (the '#' will be dealt with diagrammatically) and it is supposed to be converted to the number ff0000 in order to provide color selection. Alternatively, is there a color chooser in objective c? didn't find one in the xib objects.


Solution

  • From Objective C parse hex string to integer

    unsigned result = 0;
    NSScanner *scanner = [NSScanner scannerWithString:@"ff0000"];
    [scanner scanHexInt:&result];
    

    or using "c":

    uint32_t value;
    NSString *stringValue = @"ff0000";
    const char *string = [stringValue cStringUsingEncoding:NSUTF8StringEncoding];
    sscanf(string, "%x" , &value);