4

I have to calculate the CRC16 of a string, and have that example code:

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)
}

It works flawlessly, and the calculated CRC is for that line of code:

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

Now, I should place the contents of a text box instead of "0x31, 0x32, 0x33" and convert it to hex. How can I do this?

I need to insert in a text box only the string 313233 and then convert it to 0x31, 0x32, 0x33

Hajado
  • 41
  • 3

0 Answers0