Convert Hexadecimal to Binary (large values)

折月煮酒 提交于 2021-02-11 18:11:35

问题


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


回答1:


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)



来源:https://stackoverflow.com/questions/20294806/convert-hexadecimal-to-binary-large-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!