How to convert Hex to Binary iphone

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);