5-16 iOS 十六进制转二进制

2017-05-17  本文已影响273人  RBNote

项目中需要用到进制转换的知识, 参考了
【iOS 开发】二进制、十进制、十六进制相互转换的方法
本来很happy ,一运行就见红. 傻眼了. 拿来主义不好用啊!

NSString 拼接nil 直接崩溃.png

崩溃说明:

1.请显示考一个问题 0x0f 和 0x0F 有什么区别?
2.当为小写字符 f 时, hexDic[@"f"] 取出来的就为 nil ,因为没有对应的 f这个key. 这就是f 和 F 的区别. 字典的key是分大小写的. 十六进制data 区别区分,留给你思考吧.
3.不可变字符串拼接一个 nil 直接崩溃

解决办法

1.不管三七二十一 先将 key 转为大写
2.使用NSMutableString 可变字符串
3.代码如下

/**十六进制字符串转二进制*/
- (NSString *)getBinaryByHex:(NSString *)hex {
    NSMutableDictionary *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"];
    
    
    NSMutableString *binary = [NSMutableString string];
    for (int i = 0; i < hex.length; i++) {
        NSString *key = [hex substringWithRange:NSMakeRange(i, 1)];
        
        key = key.uppercaseString; //不管三七二十一,先转为大写字母再说
        NSString *binaryStr = hexDic[key];
        
        [binary appendString:[NSString stringWithFormat:@"%@",binaryStr]];
    }
    
    NSLog(@"十六进制转换为二进制:%@ %lu个bytes",binary,binary.length/8);
    
    return binary;
}
上一篇下一篇

猜你喜欢

热点阅读