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.

2
  • Use uint64_t to get 64 bits. Beyond that you need to describe how you get larger integers. Commented Nov 29, 2013 at 23:48
  • I'm looking into this now... is there an efficient way to incorporate that into my current code? Commented Nov 30, 2013 at 0:15

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Oh thank you! I was working along those lines but did not finish it off correctly. I changed the %ull to %llu.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.