十六进制字符串如何转换为字节

时间:2019-04-24 07:38:00

标签: objective-c swift

如何将十六进制字符串转换为字节,将字节转换为十六进制字符串? 我有oc代码,但是我不能迅速写 你能帮我吗 ? 非常感谢

+ (NSData *)convertHexToDataBytes:(NSString *)hexStr {
    NSMutableData *dataBytes = [NSMutableData data];
    int idx;
    for (idx = 0; idx + 2 <= hexStr.length; idx += 2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString *singleHexStr = [hexStr substringWithRange:range];
        NSScanner *scanner = [NSScanner scannerWithString:singleHexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [dataBytes appendBytes:&intValue length:1];
    }
    return dataBytes;
}

+ (NSString *)convertDataBytesToHex:(NSData *)dataBytes {
    if (!dataBytes || [dataBytes length] == 0) {
        return @"";
    }
    NSMutableString *hexStr = [[NSMutableString alloc] initWithCapacity:[dataBytes length]];
    [dataBytes enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char *)bytes;
        for (NSInteger i = 0; i < byteRange.length; i ++) {
            NSString *singleHexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([singleHexStr length] == 2) {
                [hexStr appendString:singleHexStr];
            } else {
                [hexStr appendFormat:@"0%@", singleHexStr];
            }
        }
    }];
    return hexStr;
}

我这样写得很快

    class func convertHex(toDataBytes hexStr: String?) -> Data? {
        var dataBytes = Data()
        var idx: Int
        idx = 0
        while idx + 2 <= (hexStr?.count ?? 0) {
            let range = NSRange(location: idx, length: 2)
            let singleHexStr = (hexStr as NSString?)?.substring(with: range)
            let scanner = Scanner(string: singleHexStr ?? "")
            var intValue: UInt
            scanner.scanHexInt32(&UInt32(intValue))
            dataBytes.append(&intValue, count: 1)
            idx += 2
        }
        return dataBytes
    }

其错误提示:无法将不变值作为inout参数传递:函数调用返回不变值如何解决?

1 个答案:

答案 0 :(得分:0)

要回答您的紧迫问题:UInt32(intValue)创建一个新的(常数)值,其地址不能用&取值。所以

var intValue: UInt
scanner.scanHexInt32(&UInt32(intValue))

应该是

var intValue: UInt32 = 0
scanner.scanHexInt32(&intValue)

dataBytes.append(&intValue, count: 1)

之所以无法编译,是因为&intValue是指向整数而不是UInt8的指针。在这里你可以做

dataBytes.append(UInt8(intValue))

因为该值已知可以容纳一个字节。

话虽如此,并不需要从StringNSString的所有转换。将该Objective-C代码更快速地翻译为Swift会

func convertHex(toDataBytes hexStr: String) -> Data {
    var dataBytes = Data()
    var startPos = hexStr.startIndex
    while let endPos = hexStr.index(startPos, offsetBy: 2, limitedBy: hexStr.endIndex) {
        let singleHexStr = hexStr[startPos..<endPos]
        let scanner = Scanner(string: String(singleHexStr))
        var intValue: UInt32 = 0
        scanner.scanHexInt32(&intValue)
        dataBytes.append(UInt8(intValue))
        startPos = endPos
    }
    return dataBytes
}

有关替代方法(包括错误检查),请参见例如 hex/binary string conversion in Swift