How do I convert binary data to hex value in obj-c?
Example:
1111 = F,
1110 = E,
0001 = 1,
0011 = 3.
I have a NSString of 10010101010011110110110011010111, and i want to convert it to hex value.
Currently I’m doing in a manual way. Which is,
-(NSString*)convertToHex:(NSString*)hexString
{
NSMutableString *convertingString = [[NSMutableString alloc] init];
for (int x = 0; x < ([hexString length]/4); x++) {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
NSString *A = [NSString stringWithFormat:@"%c", [hexString characterAtIndex:(x)]];
NSString *B = [NSString stringWithFormat:@"%c", [hexString characterAtIndex:(x*4+1)]];
NSString *C = [NSString stringWithFormat:@"%c", [hexString characterAtIndex:(x*4+2)]];
NSString *D = [NSString stringWithFormat:@"%c", [hexString characterAtIndex:(x*4+3)]];
if ([A isEqualToString:@"1"]) { a = 8;}
if ([B isEqualToString:@"1"]) { b = 4;}
if ([C isEqualToString:@"1"]) { c = 2;}
if ([D isEqualToString:@"1"]) { d = 1;}
int total = a + b + c + d;
if (total < 10) { [convertingString appendFormat:@"%i",total]; }
else if (total == 10) { [convertingString appendString:@"A"]; }
else if (total == 11) { [convertingString appendString:@"B"]; }
else if (total == 12) { [convertingString appendString:@"C"]; }
else if (total == 13) { [convertingString appendString:@"D"]; }
else if (total == 14) { [convertingString appendString:@"E"]; }
else if (total == 15) { [convertingString appendString:@"F"]; }
}
NSString *convertedHexString = convertingString;
return [convertedHexString autorelease];
[convertingString release];
}
Anyone have better suggestion? This is taking too long.
Thanks in advance.
I have never been much of a C hacker myself, but a problem like this is perfect for C, so here is my modest proposal – coded as test code to run on the Mac, but you should be able to copy the relevant bits out to use under iOS:
It seems to work, but I am sure that there is still room for improvement.