Skip to content

Instantly share code, notes, and snippets.

@antfarm
Last active July 8, 2026 17:37
Show Gist options
  • Select an option

  • Save antfarm/695fa78e0730b67eb094c77d53942216 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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

@Qata

Qata commented Oct 8, 2020

Copy link
Copy Markdown

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

@herzi

herzi commented Jul 8, 2026

Copy link
Copy Markdown

Hej hej. Thanks a lot for providing this useful code snippet! πŸ™

Bug: Int(crc) should be UInt(crc)

crc is a UInt32 and on 32bit platforms Int means Int32. When the leading bit of crc is set to 1, the number cannot be represented as Int and the process will crash:

Swift/Integers.swift:3269: Fatal error: Not enough bits to represent the passed value

Feel free to take a look at this solution to prevent the crash.

License Information: Missing

While I'm here, do you mind adding a quick license note to clarify how this snippet may be reused? Without an explicit license, the default is "all rights reserved," which makes it legally awkward for others to drop it into their own projects β€” even with attribution.

If you're happy for people to use it freely, a one-line header like // SPDX-License-Identifier: MIT (or your preference) would settle it. No worries either way β€” I just wanted to check before relying on it.

@antfarm

antfarm commented Jul 8, 2026

Copy link
Copy Markdown
Author

Feel free to steal the snippet and use it as you want. ;)

I just translated the example from the Wikipedia page to Swift and refactored it to a more functional style.

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