Reputation: 630
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
Upvotes: 7
Views: 6278
Reputation: 3684
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;
}
Upvotes: 0
Reputation: 323
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);
Upvotes: 1
Reputation: 80265
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];
}
Upvotes: 8
Reputation: 477040
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 :-)
Upvotes: 2