将0x格式字符串解析为字节swift

时间:2017-04-25 03:20:15

标签: swift string

我需要改变 这(字符串):

"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

1 个答案:

答案 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