16进制转化成二进制
在程序中需要把16进制的数字转化成二进制的数据进行输出,写了一个不是很好的方法,记录下,以备后用。
//在.h 头文件中定义16进制与二进制的转化数组
NSMutableDictionary * imgDic;
//16进制转化成二进制的方法
-(NSString *)getBinaryByhex:(NSString *)hex
{
NSMutableString *binaryString=[[NSMutableString alloc] init];
for (int i=0; i<[hex length]; i++) {
NSRange rage;
rage.length = 1;
rage.location = i;
NSString *key = [hex substringWithRange:rage];
//NSLog(@"%@",[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]);
binaryString = [NSString stringWithFormat:@"%@%@",binaryString,[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]];
}
//NSLog(@"转化后的二进制为:%@",binaryString);
return binaryString;
}
//在.m 文件的初始化如viewdidLoad 方法中初始化 转化字典
imgDic = [[NSMutableDictionary alloc] init];
[imgDic retain];
hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
[hexDic setObject:@"0000" forKey:@"0"];
[hexDic setObject:@"0001" forKey:@"1"];
[hexDic setObject:@"0010" forKey:@"2"];
[hexDic setObject:@"0011" forKey:@"3"];
[hexDic setObject:@"0100" forKey:@"4"];
[hexDic setObject:@"0101" forKey:@"5"];
[hexDic setObject:@"0110" forKey:@"6"];
[hexDic setObject:@"0111" forKey:@"7"];
[hexDic setObject:@"1000" forKey:@"8"];
[hexDic setObject:@"1001" forKey:@"9"];
[hexDic setObject:@"1010" forKey:@"A"];
[hexDic setObject:@"1011" forKey:@"B"];
[hexDic setObject:@"1100" forKey:@"C"];
[hexDic setObject:@"1101" forKey:@"D"];
[hexDic setObject:@"1110" forKey:@"E"];
[hexDic setObject:@"1111" forKey:@"F"];
//在需要的地方调用16进制转化成二进制的方法
NSString *hexString = [self getBinaryByhex:@"2AF5"];//获取出来的hexString 即为需要的16进制数据2AF5 转化成二进制后的数据