问题
-(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