1
votes

I was trying to create a CRC16-CCITT calculation in swift. But the values are not expected. I want to find out which one is wrong, my code or values of specification document. Can someone help me with this.

According to Spec,(CRC16-CCITT)
initial value : 0xFFFF
Input : 0xAA
Calculation Direction : MSB First (Left Shift)
Output : 0x0AAF

Here is the code

func crc16ccitt(data: [UInt8],seed: UInt16 = 0x1d0f, final: UInt16 = 0xffff)->UInt16{
    var crc = final
    data.forEach { (byte) in
        crc ^= UInt16(byte) << 8
        (0..<8).forEach({ _ in
            if (crc & UInt16(0x8000)) != 0 {
                crc = (crc << 1) ^ 0x1021
            }
            else {
                crc = crc << 1
            }
        })
    }
    return UInt16(crc)
}

UPDATED Answer

func crc16ccitt(data: [UInt8],seed: UInt16 = 0x1d0f, final: UInt16 = 0xffff) -> UInt16{
    var crc = final
    data.forEach { (byte) in
        crc ^= UInt16(byte) << 8
        (0..<8).forEach({ _ in
            if (crc & UInt16(0x8000)) != 0 {
                crc = (crc << 1) ^ 0x1021
            }
            else {
                crc = crc << 1
            }
            //crc = (crc & UInt16(0x8000)) != 0 ? (crc << 1) ^ 0x1021 : crc << 1
        })
    }
    return UInt16(crc ^ final)
}
1

1 Answers

4
votes

The initialization of CRC should be

var crc = final

and the update of the CRC should be

    crc ^= UInt16(byte) << 8

With those changes, your code produces the checksum 0xF550 for the input 0xAA. Note that 0xF550 is expected 0x0AAF with the bit order reversed, so that is the missing step in your calculation.

Using the methods from crc-16 cccitt problem - incorrect calculation that would be

func crc16ccitt_false() -> UInt16 {
    return crc16(data_order: straight_8, remainder_order: reverse_16, remainder: 0xffff, polynomial: 0x1021)
}

Example:

let tData = Data([0xAA])
print(String(format: "crc16ccitt_false:  %04X", tData.crc16ccitt_false())) // 0AAF