如何快速将[String]转换为[UInt8]?

时间:2018-10-31 13:22:20

标签: ios arrays swift converters

如何将我的stringArray转换为int8Array。请给我任何解决方案以转换此。 我想要下面的数组类型

let int8Array:[UInt8] = [ox55,0x55,0xff,0x01,0x0B,0x00,0x0B,0x03,0x07,0x12,0x0E,0x0C,0x10,0x09,0x12,0x0C,0x19,0x09,0xFF,0x14]

下面是我的ViewController:

class ViewController:UIViewController {
var checkSum:UInt8 = 0
override func viewDidLoad() {
    super.viewDidLoad()

let stringArray:[String] = ["0x55", "0x55", "0xff", "0x01", "0x0B", "0x38", "0x18", "0x31", "0x10", "0x18", "0x0E", "0x16", "0x31", "0x10", "0x18", "0x16", "0x30", "0x11", "0x18", "0x20", "0xE1"]
    var int8Array:[UInt8] = stringArray.map{ UInt8($0.dropFirst(2), radix: 16)! }
    int8Array.removeFirst()
    int8Array.removeFirst()
    int8Array.removeFirst()
    print(int8Array)
    for item in int8Array {
        checkSum = calculateCheckSum(crc: checkSum, byteValue: UInt8(item))
    }
    print(checkSum)

}

func calculateCheckSum(crc:UInt8, byteValue: UInt8) -> UInt8 {
    let generator: UInt8 = 0x1D

    var newCrc = crc ^ byteValue

    for _ in 1...8 {
        if (newCrc & 0x80 != 0) {
            newCrc = (newCrc << 1) ^ generator
        }
        else {
            newCrc <<= 1
        }
    }
    return newCrc
}

}

3 个答案:

答案 0 :(得分:0)

只需map的内容,您就必须删除0x才能使UInt8(_:radix:)初始化程序起作用。

let uint8Array = stringArray.map{ UInt8($0.dropFirst(2), radix: 16)! }

答案 1 :(得分:0)

如果这是一个选项,则可以切换它以指定UInt8数组并从中派生String数组。

let int8Array: [UInt8] = [0x55, 0x55, 0xa5, 0x3f]
var stringArray: [String] {
  return int8Array.map { String(format: "0x%02X", $0) }
}

print(stringArray)
// ["0x55", "0x55", "0xA5", "0x3F"]

答案 2 :(得分:0)

首先获取您的字符串数组,然后在其上调用map,然后将其映射到[UInt8](其中总结果为[[UInt8]],然后在结果上调用flatMap得到一个[UInt8]的数组..然后您可以对其进行forEach来计算您的校验和或w.e ..

[String].init().map({
    [UInt8]($0.utf8)
}).flatMap({ $0 }).forEach({
    print($0) //Print each byte or convert to hex or w/e..
})