Swift3 Swift 3将字符串转换为十六进制以进行Modbus CRC计算

Swift3 Swift 3将字符串转换为十六进制以进行Modbus CRC计算,swift3,modbus,crc16,Swift3,Modbus,Crc16,我必须计算一个字符串的CRC16,并具有该示例代码: import Foundation enum CRCType { case MODBUS case ARC } func crc16(_ data: [UInt8], type: CRCType) -> UInt16? { if data.isEmpty { return nil } let polynomial: UInt16 = 0xA001 // A001 is the bit reverse of

我必须计算一个字符串的CRC16,并具有该示例代码:

import Foundation

enum CRCType {
  case MODBUS
  case ARC
}

func crc16(_ data: [UInt8], type: CRCType) -> UInt16? {
   if data.isEmpty {
      return nil
}
let polynomial: UInt16 = 0xA001 // A001 is the bit reverse of 8005
var accumulator: UInt16
// set the accumulator initial value based on CRC type
if type == .ARC {
    accumulator = 0
}
else {
    // default to MODBUS
    accumulator = 0xFFFF
}
// main computation loop
for byte in data {
    var tempByte = UInt16(byte)
    for _ in 0 ..< 8 {
        let temp1 = accumulator & 0x0001
        accumulator = accumulator >> 1
        let temp2 = tempByte & 0x0001
        tempByte = tempByte >> 1
        if (temp1 ^ temp2) == 1 {
            accumulator = accumulator ^ polynomial
        }
    }
   }
   return accumulator
}

// try it out...

let data = [UInt8]([0x31, 0x32, 0x33])

let arcValue = crc16(data, type: .ARC)

let modbusValue = crc16(data, type: .MODBUS)

if arcValue != nil && modbusValue != nil {

  let arcStr = String(format: "0x%4X", arcValue!)
  let modbusStr = String(format: "0x%4X", modbusValue!)

   print("CRCs: ARC = " + arcStr + " MODBUS = " + modbusStr)
}
现在,我应该放置文本框的内容,而不是“0x31、0x32、0x33”,并将其转换为十六进制。我该怎么做

我只需要在文本框中插入字符串313233,然后将其转换为0x31、0x32、0x33

let data = [UInt8]([0x31, 0x32, 0x33])