我必须计算一个字符串的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)
}
它完美无缺,并且计算出的CRC用于该行代码:
let data = [UInt8]([0x31, 0x32, 0x33])
现在,我应该放置一个文本框的内容而不是“0x31,0x32,0x33”并将其转换为十六进制。我怎么能这样做?
我需要在文本框中只插入字符串313233,然后将其转换为0x31,0x32,0x33