我需要改变 这(字符串):
"0xab,0xcd,0x00,0x01,0xff,0xff,0xab,0xcd,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00"
到(字节)
[0xab,0xcd,0x00,0x01,0xff,0xff,0xab,0xcd,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 ]
使用swift
答案 0 :(得分:4)
一个选项是从每个字符串中删除0x
,然后将剩余的逗号分隔值拆分为数组。最后,使用flatMap
将每个十六进制字符串转换为数字。
// Your original string
let hexString = "0xab,0xcd,0x00,0x01,0xff,0xff,0xab,0xcd,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00"
// Remove all of the "0x"
let cleanString = hexString.replacingOccurrences(of: "0x", with: "")
// Create an array of hex strings
let hexStrings = cleanString.components(separatedBy: ",")
// Convert the array of hex strings into bytes (UInt8)
let bytes = hexStrings.flatMap { UInt8($0, radix: 16) }
如果有任何值不是有效的十六进制字节值,我使用了flatMap
。