landfill
landfill

Reputation: 41

Convert Hexadecimal to Binary (large values)

-(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.

Upvotes: 0

Views: 762

Answers (1)

rmaddy
rmaddy

Reputation: 318804

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)

Upvotes: 2

Related Questions