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];
}

Leave a Comment