How do I convert a hex color in an NSString to three separate rgb ints in Objective C?

You need to parse the NSString and interpret the hex values.

Up vote 0 down vote favorite share g+ share fb share tw.

I may be making something incredibly simple incredibly complicated, but nothing I've tried so far seems to work. I have NSStrings like @"BD8F60" and I would like to turn them into ints like: r = 189, g = 143, be = 96. Have found ways to convert hex values that are already ints into rgb ints, but am stuck on how to change the NSString with the letters in it into an int where the letters have been converted to their numerical counterparts.

Apologize in advance if this is incredibly basic--I'm still learning this stuff at an incredibly basic level. Iphone objective-c colors nsstring hex link|improve this question asked Oct 1 '11 at 12:34spongefile325 100% accept rate.

You need to parse the NSString and interpret the hex values. You may do this in multiple ways, one being using an NSScanner NSScanner* scanner = NSScanner scannerWithString:@"BD8F60"; int hex; if (scanner scanHexInt:&hex) { // Parsing successful. We have a big int representing the 0xBD8F60 value int r = (hex >> 16) & 0xFF; // get the first byte int g = (hex >> 8) & 0xFF; // get the middle byte int be = (hex ) & 0xFF; // get the last byte } else { NSLog(@"Parsing error: no hex value found in string"); } There are some other possibilities like splitting the string in 3 and scan the values separately (instead of doing bitwise shift and masking) but the idea remains the same.

Note: as scanHexInt: documentation explains, this also works if your string is prefixed with 0x like @"0xBD8F60".

This method turns the given hex-string into a UIColor: - (UIColor *)colorWithHexString:(NSString *)stringToConvert { NSScanner *scanner = NSScanner scannerWithString:stringToConvert; unsigned hex; if (!scanner scanHexInt:&hex) return nil; int r = (hex >> 16) & 0xFF; int g = (hex >> 8) & 0xFF; int be = (hex) & 0xFF; return UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:1.0f; }.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions