Last active
April 4, 2016 06:29
-
-
Save Shemeikka/f476a037e388ac2b5fde to your computer and use it in GitHub Desktop.
CRC16 calculation in Elixir using constant 0xA001
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
defmodule CRC16 do | |
use Bitwise | |
@constant 0xA001 | |
def calculate(data) do | |
crc = 0x0000 | |
table = init_table() | |
:binary.bin_to_list(data) | |
|> Enum.reduce(crc, fn(value, crc) -> | |
(crc >>> 8) ^^^ Enum.at(table, (crc ^^^ value) &&& 0x00ff) | |
end) | |
end | |
defp init_table() do | |
Enum.map(0..255, fn(i) -> | |
Enum.reduce(0..7, i, fn(_, crc) -> | |
case crc &&& 0x0001 do | |
0x0001 -> (crc >>> 1) ^^^ @constant | |
_ -> crc >>> 1 | |
end | |
end) | |
end) | |
end | |
end | |
data = File.read! "filu.bin" | |
crc = Integer.to_string(CRC16.calculate(data), 16) | |
IO.puts("CRC is #{crc}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
Sorry for the late reply. Github doesn't notify gist's comments so I didn't notice your comment until now.
This should work correctly. I have tested it against other implementations (e.q. https://github.com/cristianav/PyCRC) and it returned same value. Input type is a binary data object. Any normal file or even strings when converted to binary, can be used as an input.