Objective-C中是否有将十六进制字符串转换为字节的方法?例如@"1156FFCD3430AA22"unsigned char array {0x11, 0x56, 0xFF, ...}

最佳答案

我能想到的最快的NSString类别实现(一些示例):

- (NSData *)dataFromHexString {
    const char *chars = [self UTF8String];
    int i = 0, len = self.length;

    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;

    while (i < len) {
        byteChars[0] = chars[i++];
        byteChars[1] = chars[i++];
        wholeByte = strtoul(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }

    return data;
}

它比wookay的解决方案快近8倍。 NSScanner相当慢。

关于objective-c - NSString(hex)转换为字节,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2501033/

10-11 15:43