How to convert hex to binary iphone

I need to convert a hexadecimal string to binary form in objective-c, can someone please direct me? For example, if I have a 7fefff78 hexadecimal string, do I want to convert it to 1111111111011111111111101111000?

BR, Suppi

+7
source share
4 answers

Good 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]; } 
+8
source

Just convert each digit one at a time: 0 -> 0000 , 7 -> 0111 , F -> 1111 , etc. A small lookup table can make this very concise.

The beauty of the bases of numbers, which are powers of another base :-)

+2
source

If 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); 
+1
source

I agree with Kerrek SB's answer and have tried this. His work is 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; } 
0
source

All Articles