数据流的16进制高效编码

16进制编码,转成字符串
+ (NSString *)hexStringForData:(NSData *)data {
    static const u_char HexCharMap[] = "0123456789abcdef";
    Byte* bytes = (Byte*) [self bytes];
    Byte* bytesHex = (Byte*) malloc([self length]*2);
    for (NSUInteger i = 0, j = 0; i < [self length]; i++, j+=2) {
        bytesHex[j+1] = HexCharMap[ bytes[i] & 0x0f ];
        bytesHex[j  ] = HexCharMap[(bytes[i] & 0xf0) >> 4];
    }
    return [[NSString alloc] initWithBytesNoCopy:bytesHex length:[self length]*2 encoding:(NSASCIIStringEncoding) freeWhenDone:YES];
}
16进制编码逆过程
+ (NSData *)dataFromHexString:(NSString *)hexString {
    NSUInteger size = [hexString length] / 2;
    Byte* result = (Byte*) malloc(size);
    bzero(result, size);
    const char * cstring = [hexString cStringUsingEncoding:NSUTF8StringEncoding];
    for (int i = 0, j = 0; i < size; i++, j += 2) {
        result[i] = (Byte) ((digittoint(cstring[j]) << 4)  | digittoint(cstring[j+1]));
    }
    
    return [NSData dataWithBytesNoCopy: result length:size freeWhenDone:YES];
}

总结

无意中搜到了C函数 digittoint,已经可以把16进制字符转成数值,所以欣喜之余,发现可以抛弃网上的NSScaner方案(不断构造新scanner来解析)。如果刚好你看到,觉得有用,那就留个赞。:)

你可能感兴趣的:(数据流的16进制高效编码)