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.
Asked
Active
Viewed 5,599 times
4
-
http://stackoverflow.com/questions/3648411/objective-c-parse-hex-string-to-integer – Fls'Zen Dec 31 '12 at 21:14
-
possible duplicate of [How to convert HEX RGB color codes to UIColor?](http://stackoverflow.com/questions/3805177/how-to-convert-hex-rgb-color-codes-to-uicolor) – rob mayoff Dec 31 '12 at 21:19
-
Fis'Zen, the link you provide deals with converting hexadecimal to decimal, it is not what I asked. @rob, you are right, but since I did search for an answer and couldn't find that post (it uses a different way to describe the problem) it might be better to leave both intact, if only so people can find my question and see your link, maybe? – Dec 31 '12 at 21:45
-
Note that there is really no such thing as a hexadecimal number, that is just a display type. So the question might be better as: Convert a hexadecimal string representation to an integer. – zaph Dec 31 '12 at 22:05
2 Answers
14
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);
1
You can use the below line for conversion. Its just one line code:
NSString *hexString = @"01FFFFAB";
length = (UInt64)strtoull([sizeLine UTF8String], NULL, 16);
NSLog(@"The required Length is %d", length);
Happy Coding!!!

Sahil Mahajan
- 3,922
- 2
- 29
- 43