Skip to content

Instantly share code, notes, and snippets.

@antfarm
Last active March 29, 2023 10:52
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save antfarm/695fa78e0730b67eb094c77d53942216 to your computer and use it in GitHub Desktop.
Save antfarm/695fa78e0730b67eb094c77d53942216 to your computer and use it in GitHub Desktop.
CRC32 checksum generation in a few lines of Swift 5. https://en.wikipedia.org/wiki/Cyclic_redundancy_check#CRC-32_algorithm
class CRC32 {
static var table: [UInt32] = {
(0...255).map { i -> UInt32 in
(0..<8).reduce(UInt32(i), { c, _ in
(c % 2 == 0) ? (c >> 1) : (0xEDB88320 ^ (c >> 1))
})
}
}()
static func checksum(bytes: [UInt8]) -> UInt32 {
return ~(bytes.reduce(~UInt32(0), { crc, byte in
(crc >> 8) ^ table[(Int(crc) ^ Int(byte)) & 0xFF]
}))
}
}
@dcwatson
Copy link

Thanks for this! I used checksum<T: DataProtocol>(bytes: T) to accept Data as well as [UInt8]

@Qata
Copy link

Qata commented Oct 8, 2020

I have a personal vendetta against the ternary operator. Here's a simplification. ((0xEDB88320 * (c % 2)) ^ (c >> 1))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment