Skip to content

Instantly share code, notes, and snippets.

@Shemeikka
Last active April 4, 2016 06:29
Show Gist options
  • Save Shemeikka/f476a037e388ac2b5fde to your computer and use it in GitHub Desktop.
Save Shemeikka/f476a037e388ac2b5fde to your computer and use it in GitHub Desktop.
CRC16 calculation in Elixir using constant 0xA001
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}")
@kmittal01
Copy link

Hi, does this implementation works correctly? Can you tell me what is the type of input that you are using for this? (an example input would be great!). Thanks.

@Shemeikka
Copy link
Author

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.

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