美文网首页程序开发
iOS开发丨16进制字符串NSString和NSData互转

iOS开发丨16进制字符串NSString和NSData互转

作者: 炼心术师 | 来源:发表于2019-12-17 13:42 被阅读0次

有些时候我们会用到十六进制字符串的字节码来转换成NSData并进行操作,方法如下:

// NSData转普通字符串
+ (NSString *)DataToString:(NSData *)data {
    NSMutableArray *strArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < data.length; i++) {
        NSString *utf8Str = [NSString stringWithUTF8String:[[data subdataWithRange:NSMakeRange(i, 1)] bytes]];
        if (utf8Str) {
            [strArr addObject:utf8Str];
        }
    }
    return [strArr componentsJoinedByString:@""];
}

// NSData转十六进制字符串
+ (NSString *)DataToHexString:(NSData *)data {
    NSUInteger length = data.length;
    NSMutableString *hexStr = [NSMutableString stringWithCapacity:length * 2];
    const unsigned char *byte = data.bytes;
    for (int i = 0; i < length; i++, byte++) {
        [hexStr appendFormat:@"%02X", *byte];
    }
    return hexStr;
}

// 十六进制字符串转NSData
+ (NSData *)HexStringToData:(NSString *)hexStr {
    hexStr = [hexStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    hexStr = [hexStr lowercaseString];
    NSUInteger len = hexStr.length;
    if (!len) return nil;
    unichar *buf = malloc(sizeof(unichar) * len);
    if (!buf) return nil;
    [hexStr getCharacters:buf range:NSMakeRange(0, len)];
    
    NSMutableData *result = [NSMutableData data];
    unsigned char bytes;
    char str[3] = { '\0', '\0', '\0' };
    int i;
    for (i = 0; i < len / 2; i++) {
        str[0] = buf[i * 2];
        str[1] = buf[i * 2 + 1];
        bytes = strtol(str, NULL, 16);
        [result appendBytes:&bytes length:1];
    }
    free(buf);
    return result;
}

相关文章

网友评论

    本文标题:iOS开发丨16进制字符串NSString和NSData互转

    本文链接:https://www.haomeiwen.com/subject/utusnctx.html