我正在尝试将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")