当前位置 : 主页 > 手机开发 > 其它 >

如何在Swift 3中将HexString转换为ByteArray

来源:互联网 收集:自由互联 发布时间:2021-06-11
我正在尝试将hexString转换为字节数组([UInt8])我搜索到了所有地方但找不到解决方案.下面是我的快速2代码 func stringToBytes(_ string: String) - [UInt8]? { let chars = Array(string) let length = chars.count i
我正在尝试将hexString转换为字节数组([UInt8])我搜索到了所有地方但找不到解决方案.下面是我的快速2代码

func stringToBytes(_ string: String) -> [UInt8]? {
    let chars = Array(string)
    let length = chars.count
    if length & 1 != 0 {
        return nil
    }
    var bytes = [UInt8]()
    bytes.reserveCapacity(length/2)
    for var i = 0; i < length; i += 2 {
        if let a = find(hexChars, chars[i]),
            let b = find(hexChars, chars[i+1]) {
            bytes.append(UInt8(a << 4) + UInt8(b))
        } else {
            return nil
        }
    }
    return bytes
}

示例Hex

十六进制:“7661706f72”

expectedOutput:“蒸汽”

此代码可以生成与swift 2代码相同的输出.

func stringToBytes(_ string: String) -> [UInt8]? {
    let length = string.characters.count
    if length & 1 != 0 {
        return nil
    }
    var bytes = [UInt8]()
    bytes.reserveCapacity(length/2)
    var index = string.startIndex
    for _ in 0..<length/2 {
        let nextIndex = string.index(index, offsetBy: 2)
        if let b = UInt8(string[index..<nextIndex], radix: 16) {
            bytes.append(b)
        } else {
            return nil
        }
        index = nextIndex
    }
    return bytes
}

let bytes = stringToBytes("7661706f72")
print(String(bytes: bytes!, encoding: .utf8)) //->Optional("vapor")
网友评论