如何将 NSData 转换为 NSString Hex 字符串? [英] How to convert an NSData into an NSString Hex string?

查看:25
本文介绍了如何将 NSData 转换为 NSString Hex 字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 NSData 对象上调用 -description 时,我看到一个漂亮的 NSData 对象字节的十六进制字符串,例如:

When I call -description on an NSData object, I see a pretty Hex string of the NSData object's bytes like:

<f6e7cd28 0fc5b5d4 88f8394b af216506 bc1bba86 4d5b483d>

我想将数据的这种表示(减去 lt/gt 引号)放入内存中的 NSString 中,以便我可以使用它.. 我不想调用-[NSData description] 然后只修剪 lt/gt 引号(因为我认为这不是 NSData 公共接口的保证方面,并且在未来).

I'd like to get this representation of the data (minus the lt/gt quotes) into an in-memory NSString so I can work with it.. I'd prefer not to call -[NSData description] and then just trim the lt/gt quotes (because I assume that is not a guaranteed aspect of NSData's public interface and is subject change in the future).

NSData 对象的这种表示转化为 NSString 对象的最简单方法是什么(除了调用 -description)?

What's the simplest way to get this representation of an NSData object into an NSString object (other than calling -description)?

推荐答案

请记住,任何 String(format: ...) 解决方案都会非常慢(对于大数据)

Keep in mind that any String(format: ...) solution will be terribly slow (for large data)

NSData *data = ...;
NSUInteger capacity = data.length * 2;
NSMutableString *sbuf = [NSMutableString stringWithCapacity:capacity];
const unsigned char *buf = data.bytes;
NSInteger i;
for (i=0; i<data.length; ++i) {
  [sbuf appendFormat:@"%02X", (NSUInteger)buf[i]];
}

如果您需要更高性能的东西,试试这个:

If you need something more performant try this:

static inline char itoh(int i) {
    if (i > 9) return 'A' + (i - 10);
    return '0' + i;
}

NSString * NSDataToHex(NSData *data) {
    NSUInteger i, len;
    unsigned char *buf, *bytes;
    
    len = data.length;
    bytes = (unsigned char*)data.bytes;
    buf = malloc(len*2);
    
    for (i=0; i<len; i++) {
        buf[i*2] = itoh((bytes[i] >> 4) & 0xF);
        buf[i*2+1] = itoh(bytes[i] & 0xF);
    }
    
    return [[NSString alloc] initWithBytesNoCopy:buf
                                          length:len*2
                                        encoding:NSASCIIStringEncoding
                                    freeWhenDone:YES];
}

Swift 版本


private extension Data {
    var hexadecimalString: String {
        let charA: UInt8 = 0x61
        let char0: UInt8 = 0x30
        func byteToChar(_ b: UInt8) -> Character {
            Character(UnicodeScalar(b > 9 ? charA + b - 10 : char0 + b))
        }
        let hexChars = flatMap {[
            byteToChar(($0 >> 4) & 0xF),
            byteToChar($0 & 0xF)
        ]}
        return String(hexChars)
    }
}

这篇关于如何将 NSData 转换为 NSString Hex 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆