我需要在objective-c中将十六进制字符串转换为二进制形式,有人可以指导我吗? 例如,如果我有一个十六进制字符串7fefff78,我想将其转换为1111111111011111111111101111000?
BR, Suppi
答案 0 :(得分:8)
很好的递归解决方案......
NSString *hex = @"49cf3e";
NSUInteger hexAsInt;
[[NSScanner scannerWithString:hex] scanHexInt:&hexAsInt];
NSString *binary = [NSString stringWithFormat:@"%@", [self toBinary:hexAsInt]];
-(NSString *)toBinary:(NSUInteger)input
{
if (input == 1 || input == 0)
return [NSString stringWithFormat:@"%u", input];
return [NSString stringWithFormat:@"%@%u", [self toBinary:input / 2], input % 2];
}
答案 1 :(得分:2)
只需逐个转换每个数字:0 -> 0000
,7 -> 0111
,F -> 1111
等。一个小的查找表可以使这个非常简洁。
作为另一个基地的力量的数字基础的美丽: - )
答案 2 :(得分:1)
如果您需要前导零,例如18返回00011000而不是11000
-(NSString *)toBinary:(NSUInteger)input strLength:(int)length{
if (input == 1 || input == 0){
NSString *str=[NSString stringWithFormat:@"%u", input];
return str;
}
else {
NSString *str=[NSString stringWithFormat:@"%@%u", [self toBinary:input / 2 strLength:0], input % 2];
if(length>0){
int reqInt = length * 4;
for(int i= [str length];i < reqInt;i++){
str=[NSString stringWithFormat:@"%@%@",@"0",str];
}
}
return str;
}
}
NSString *hex = @"58";
NSUInteger hexAsInt;
[[NSScanner scannerWithString:hex] scanHexInt:&hexAsInt];
NSString *binary = [NSString stringWithFormat:@"%@", [self toBinary:hexAsInt strLength:[hex length]]];
NSLog(@"binario %@",binary);
答案 3 :(得分:0)
我同意kerrek SB的回答并尝试了这一点。 它的工作对我来说。
+(NSString *)convertBinaryToHex:(NSString *) strBinary
{
NSString *strResult = @"";
NSDictionary *dictBinToHax = [[NSDictionary alloc] initWithObjectsAndKeys:
@"0",@"0000",
@"1",@"0001",
@"2",@"0010",
@"3",@"0011",
@"4",@"0100",
@"5",@"0101",
@"6",@"0110",
@"7",@"0111",
@"8",@"1000",
@"9",@"1001",
@"A",@"1010",
@"B",@"1011",
@"C",@"1100",
@"D",@"1101",
@"E",@"1110",
@"F",@"1111", nil];
for (int i = 0;i < [strBinary length]; i+=4)
{
NSString *strBinaryKey = [strBinary substringWithRange: NSMakeRange(i, 4)];
strResult = [NSString stringWithFormat:@"%@%@",strResult,[dictBinToHax valueForKey:strBinaryKey]];
}
return strResult;
}