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