Created
May 5, 2022 07:18
-
-
Save massimilianochiodi/8baa4c308f1b6701c7757bdf02fb9479 to your computer and use it in GitHub Desktop.
Calculate CRC CCITT Swift 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Calcola il crc16 ( CRC-CCITT ) di un array di bytes nella rappresentazione UInt8 | |
/// | |
/// - Parameters: | |
/// - input: Array di UInt8 | |
/// - Returns: valore in due bytes in formato UInt16 | |
public func getCRC(input : [UInt8]) -> UInt16 { | |
if input.count == 0 { return 0 } | |
var crc: UInt16 = 0xFFFF; // initial value | |
let polynomial: UInt16 = 0x1021; // 0001 0000 0010 0001 (0, 5, 12) | |
for b in input { | |
var i = 0 | |
while (i < 8){ | |
let bit = ((b >> (7-i) & 1) == 1) // boolean | |
let c15 = ((crc >> 15 & 1) == 1) // boolean | |
crc <<= 1 | |
if (XORCase(lhs: bit, rhs: c15)) { // equivale a bit ^ c15 | |
crc ^= polynomial | |
} | |
i += 1 | |
} | |
crc &= 0xffff | |
} | |
return crc | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment