0
-(NSString *)toBinary:(NSUInteger)input
{
    if (input == 1 || input == 0)
        return [NSString stringWithFormat:@"%u", input];
    return [NSString stringWithFormat:@"%@%u", [self toBinary:input / 2], input % 2];
}

NSString *hex = txtHexInput.text;
NSUInteger hexAsInt;
[[NSScanner scannerWithString:hex] scanHexInt:&hexAsInt];
NSString *binary = [NSString stringWithFormat:@"%@", [self toBinary:hexAsInt]];
txtBinaryInput.text = binary;

The above code works great... that is until you need to exceed 32 bits. Any pointers to converting hex to binary for larger than 32 bit values? Thank you.

Pradhyuman sinh
  • 3,936
  • 1
  • 23
  • 38
landfill
  • 41
  • 2

1 Answers1

2

You can get 64 bits using uint64_t or unsigned long long.

-(NSString *)toBinary:(unsigned long long)input
{
    if (input == 1 || input == 0)
        return [NSString stringWithFormat:@"%llu", input];
    return [NSString stringWithFormat:@"%@%llu", [self toBinary:input / 2], input % 2];
}

NSString *hex = txtHexInput.text;
unsigned long long hexAsULL;
[[NSScanner scannerWithString:hex] scanHexLongLong:&hexAsULL];
NSString *binary = [NSString stringWithFormat:@"%@", [self toBinary:hexAsULL]];
txtBinaryInput.text = binary;

This will give you numbers from 0 to 18,446,744,073,709,551,615 (decimal)

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Oh thank you! I was working along those lines but did not finish it off correctly. I changed the %ull to %llu. – landfill Nov 30 '13 at 00:36