将十六进制转换为二进制(大值)

时间:2013-11-29 23:44:02

标签: ios binary hex

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

上面的代码效果很好......直到你需要超过32位。任何指针将十六进制转换为二进制以获得大于32位的值?谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用uint64_tunsigned long long获得64位。

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

这将为您提供0到18,446,744,073,709,551,615(十进制)的数字