HEX to UIColorfromRGB - iphone

I'm following a tutorial here
It's fairly straight forward and simple, only 2 steps. But on the last step, I have the HEX code in a UITextField as hexText.text, but how do i put that into UIColorFromRGB?

here is a solution that avoids the macro stuff. You can add it to a category to UIColor and use it more nicely.

Sorin has the right idea here I think. Much more cocoa-like, and will result in fewer headaches. To answer your question at a high level, you'd need to convert your string to a hexadecimal number, and then pass that resulting value in to the macro. I think you'd be better served just passing the string value into the category listed in Sorin's link.

This will solve any case
+ (UIColor *) colorWithHexString: (NSString *) stringToConvert{
NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
unsigned int r, g, b,alpha = 1;
NSRange range;
range.location = 0;
range.length = 2;
// String should be 6 or 8 characters
if ([cString length] < 6) return [UIColor blackColor];
// strip 0X if it appears
if ([cString hasPrefix:#"0X"]) cString = [cString substringFromIndex:2];
if ([cString hasPrefix:#"#"]) cString = [cString substringFromIndex:1];
if ([cString length] == 8) {
[[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&alpha];
cString = [cString substringFromIndex:2];
}
if ([cString length] != 6) return [UIColor blackColor];
// Separate into r, g, b substrings
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f)
green:((float) g / 255.0f)
blue:((float) b / 255.0f)
alpha:((float) alpha / 255.0f)];
}

Related

Convert Hex to ASCII number on Objective-c

I have an one hexa decimal number
535443326663315634524877795678586b536854535530342f44526a795744716133353942704359697a6b736e446953677171555473
I want to convert this number to ASCII format which will look like this
STC2fc1V4RHwyVxXkShTSU04/DRjyWDqa359BpCYizksnDiSgqqUTsYUOcHKHNMJOdqR1/TQywpD9a9xhri
i have seen solutions here but none of them is useful to me
NSString containing hex convert to ascii equivalent
i checked here but they give different result. Any help
This works perfectly
- (NSString *)stringFromHexString:(NSString *)hexString {
// The hex codes should all be two characters.
if (([hexString length] % 2) != 0)
return nil;
NSMutableString *string = [NSMutableString string];
for (NSInteger i = 0; i < [hexString length]; i += 2) {
NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
NSInteger decimalValue = 0;
sscanf([hex UTF8String], "%x", &decimalValue);
[string appendFormat:#"%c", decimalValue];
NSLog(#"string--%#",string);
}
_hexString1=string;
NSLog(#"string ---%#",_hexString1);
return string;
}
If you're starting with NSData * you could get the ASCII string this way:
NSData *someData = [NSData dataWithHexString:#"ABC123"];
NSString *asciiString = [[NSString alloc] initWithData: someData encoding:NSASCIIStringEncoding];

hex a to binary

i am trying to convert my hex value to binary value , but i am facing little problem .
as i am new trying to learn my faults .
my code :
NSMutableString *str;
NSString *dd = #"192:168:1:2:0B:2:D:00";
NSCharacterSet *donotwant1 = [NSCharacterSet characterSetWithCharactersInString:#":""];
dd =[[dd componentsSeparatedByCharactersInSet:donotwant1] componentsJoinedByString:#" "];
NSMutableArray *array = [[dd componentsSeparatedByString:#" "] mutableCopy];
[array removeObjectAtIndex:0];
//NSLog(#"%#",array);
for (int j=0; j<[array count]; j++) {
NSScanner *scan = [NSScanner scannerWithString:[array objectAtIndex:j]];
unsigned int i=0;
if ([scan scanHexInt:&i]) {
// NSLog(#"numbner is %ustr", i);
}
NSInteger theNumber = i;
str = [NSMutableString string];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1) {
// Prepend "0" or "1", depending on the bit
[str insertString:((numberCopy & 1) ? #"1" : #"0") atIndex:0];
[array removeObjectAtIndex:j];
[array insertObject:str atIndex:j];
}
}
NSLog(#"Binary version: %#", array);
I'm getting
1,1100,11001111,1111,1111,11101111.....
in my code 0 values are eliminated . i want 8bits like(00000001,00001100.....) can any one tell me the reason
When the most significant bit is reached, your algorithm stops the conversion. Why not force the loop to always execute 8 times?
for (int numberCopy = theNumber, int i = 0; i < 8; numberCopy >>= 1, i++) {
// loop body here
}
By the way, here's a cleaner/shorter/simpler approach that doesn't involve highly superfluous copying and uses characters instead of string objects for hyper efficiency (just kidding, I'm all against micro-optimizations, but I feel like inserting an NSString before another one is unnecessary, especially if the number of bits is known and constant). This also assumes UTF-8 and exploits the fact that hexadecimal and binary representation have a very nice relationship, 16 being the 4th power of 2:
NSString *dd = #"01:0C:CF:0F:EF:AF:BD:00";
NSArray *bytes = [dd componentsSeparatedByString:#":"];
NSMutableArray *binaries = [NSMutableArray array];
NSString *lookup[256];
lookup['0'] = #"0000";
lookup['1'] = #"0001";
lookup['2'] = #"0010";
lookup['3'] = #"0011";
lookup['4'] = #"0100";
lookup['5'] = #"0101";
lookup['6'] = #"0110";
lookup['7'] = #"0111";
lookup['8'] = #"1000";
lookup['9'] = #"1001";
lookup['A'] = #"1010";
lookup['B'] = #"1011";
lookup['C'] = #"1100";
lookup['D'] = #"1101";
lookup['E'] = #"1110";
lookup['F'] = #"1111";
for (NSString *s in bytes) {
unichar n1 = [s characterAtIndex:0];
unichar n0 = [s characterAtIndex:1];
[binaries addObject:[lookup[n1] stringByAppendingString:lookup[n0]]];
}
NSLog(#"%#", binaries);

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

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, b = 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.
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 b = (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". Does not automatically work with strings prefixed by a hash like #"#BD8F60". Use a substring in this case.
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 b = (hex) & 0xFF;
return [UIColor colorWithRed:r / 255.0f
green:g / 255.0f
blue:b / 255.0f
alpha:1.0f];
}
a category on UIColor that also deals with alpha values rrggbbaa and short forms as rgb or rgba.
use it it like
UIColor *color = [UIColor colorFromHexString:#"#998997FF"]; //#RRGGBBAA
or
UIColor *color = [UIColor colorFromHexString:#"998997FF"]; //RRGGBBAA
or
UIColor *color = [UIColor colorFromHexString:#"0x998997FF"];// 0xRRGGBBAA
or
UIColor *color = [UIColor colorFromHexString:#"#999"]; // #RGB -> #RRGGBB
or
UIColor *color = [UIColor colorFromHexString:#"#9acd"]; // #RGBA -> #RRGGBBAA
#implementation UIColor (Creation)
+(UIColor *)_colorFromHex:(NSUInteger)hexInt
{
int r,g,b,a;
r = (hexInt >> 030) & 0xFF;
g = (hexInt >> 020) & 0xFF;
b = (hexInt >> 010) & 0xFF;
a = hexInt & 0xFF;
return [UIColor colorWithRed:r / 255.0f
green:g / 255.0f
blue:b / 255.0f
alpha:a / 255.0f];
}
+(UIColor *)colorFromHexString:(NSString *)hexString
{
hexString = [hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if ([hexString hasPrefix:#"#"])
hexString = [hexString substringFromIndex:1];
else if([hexString hasPrefix:#"0x"])
hexString = [hexString substringFromIndex:2];
int l = [hexString length];
if ((l!=3) && (l!=4) && (l!=6) && (l!=8))
return nil;
if ([hexString length] > 2 && [hexString length]< 5) {
NSMutableString *newHexString = [[NSMutableString alloc] initWithCapacity:[hexString length]*2];
[hexString enumerateSubstringsInRange:NSMakeRange(0, [hexString length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring,
NSRange substringRange,
NSRange enclosingRange,
BOOL *stop)
{
[newHexString appendFormat:#"%#%#", substring, substring];
}];
hexString = newHexString;
}
if ([hexString length] == 6)
hexString = [hexString stringByAppendingString:#"ff"];
NSScanner *scanner = [NSScanner scannerWithString:hexString];
unsigned hexNum;
if (![scanner scanHexInt:&hexNum])
return nil;
return [self _colorFromHex:hexNum];
}
#end
use it in swift:
add #include "UIColor+Creation.h" to Bridging Header
use
UIColor(fromHexString:"62AF3C")

How to convert Hex to Binary iphone

I need to convert a hex string to binary form in objective-c, Could someone please guide me?
For example if i have a hex string 7fefff78, i want to convert it to 1111111111011111111111101111000?
BR,
Suppi
Nice recursive solution...
NSString *hex = #"49cf3e";
NSUInteger hexAsInt;
[[NSScanner scannerWithString:hex] scanHexInt:&hexAsInt];
NSString *binary = [NSString stringWithFormat:#"%#", [self toBinary:hexAsInt]];
-(NSString *)toBinary:(NSUInteger)input
{
if (input == 1 || input == 0)
return [NSString stringWithFormat:#"%u", input];
return [NSString stringWithFormat:#"%#%u", [self toBinary:input / 2], input % 2];
}
Simply convert each digit one by one: 0 -> 0000, 7 -> 0111, F -> 1111, etc. A little lookup table could make this very concise.
The beauty of number bases that are powers of another base :-)
In case you need leading zeros, for example 18 returns 00011000 instead of 11000
-(NSString *)toBinary:(NSUInteger)input strLength:(int)length{
if (input == 1 || input == 0){
NSString *str=[NSString stringWithFormat:#"%u", input];
return str;
}
else {
NSString *str=[NSString stringWithFormat:#"%#%u", [self toBinary:input / 2 strLength:0], input % 2];
if(length>0){
int reqInt = length * 4;
for(int i= [str length];i < reqInt;i++){
str=[NSString stringWithFormat:#"%#%#",#"0",str];
}
}
return str;
}
}
NSString *hex = #"58";
NSUInteger hexAsInt;
[[NSScanner scannerWithString:hex] scanHexInt:&hexAsInt];
NSString *binary = [NSString stringWithFormat:#"%#", [self toBinary:hexAsInt strLength:[hex length]]];
NSLog(#"binario %#",binary);
I agree with kerrek SB's answer and tried this.
Its work for me.
+(NSString *)convertBinaryToHex:(NSString *) strBinary
{
NSString *strResult = #"";
NSDictionary *dictBinToHax = [[NSDictionary alloc] initWithObjectsAndKeys:
#"0",#"0000",
#"1",#"0001",
#"2",#"0010",
#"3",#"0011",
#"4",#"0100",
#"5",#"0101",
#"6",#"0110",
#"7",#"0111",
#"8",#"1000",
#"9",#"1001",
#"A",#"1010",
#"B",#"1011",
#"C",#"1100",
#"D",#"1101",
#"E",#"1110",
#"F",#"1111", nil];
for (int i = 0;i < [strBinary length]; i+=4)
{
NSString *strBinaryKey = [strBinary substringWithRange: NSMakeRange(i, 4)];
strResult = [NSString stringWithFormat:#"%#%#",strResult,[dictBinToHax valueForKey:strBinaryKey]];
}
return strResult;
}

Unrecognized selector woes

I'm puzzled... I have this function "colorWithHexString"... when I include it in the viewcontroller that's calling it then it works fine. But when I move it to a separate "BSJax" class and call it with the same input parameter it throws an unrecognized selector error. Here's the call:
BSjax *bsjax = [BSjax new];
NSString *hexString = [NSString stringWithString:#"CCCCFF"];
[self.view setBackgroundColor:[bsjax colorWithHexString:hexString]];
I'm pretty sure there's something about the way I'm calling the function that prevents it from working as a bsjax method. Any feedback will be appreciated.
BSjax.h includes:
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert;
... and BSjax.m includes:
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert
{
NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) NSLog(#"colorWithHexString called with parameter < 6 characters in length");
// strip 0X if it appears
if ([cString hasPrefix:#"0X"]) cString = [cString substringFromIndex:2];
if ([cString length] != 6) NSLog(#"colorWithHexString called with parameter != 6 characters in length");
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f)
green:((float) g / 255.0f)
blue:((float) b / 255.0f)
alpha:1.0f];
}
You are trying to call a class method on an instance.
Notice the +:
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert;
It means you can only call the method as [ClassName classmethod]
And then here you are trying to use the method with an instance [instanceObject classmethod]:
BSjax *bsjax = [BSjax new];
[self.view setBackgroundColor:[bsjax colorWithHexString:hexString]];
Try changing it to:
[self.view setBackgroundColor:[BSjax colorWithHexString:hexString]];
And that should set you straight.
Is colorWithHexString declared in #interface BSjax in a header, and did you #import that header into the source file where the error is reported?
Edit:
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert;
The above code (the +) declares a class method, meaning it should be called with the class name. You are calling it with an instance of the class, for which it is not defined. Try:
[self.view setBackgroundColor:[BSjax colorWithHexString:hexString]];