将0x格式的字符串解析为字节快速

Sus*_*djo 0 string swift

我需要更改此(字符串):

"0xab,0xcd,0x00,0x01,0xff,0xff,0xab,0xcd,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00"
Run Code Online (Sandbox Code Playgroud)

至(字节)

[0xab,0xcd,0x00,0x01,0xff,0xff,0xab,0xcd,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 ]
Run Code Online (Sandbox Code Playgroud)

使用迅捷

rma*_*ddy 5

一种选择是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) }
Run Code Online (Sandbox Code Playgroud)

我使用flatMap了一些无效的十六进制字节值的情况。