Skip to content

Instantly share code, notes, and snippets.

@girorme
Last active July 15, 2023 06:18
Show Gist options
  • Save girorme/0d348c3c1556e1945a20cb1f838d72e1 to your computer and use it in GitHub Desktop.
Save girorme/0d348c3c1556e1945a20cb1f838d72e1 to your computer and use it in GitHub Desktop.
Extract binary magic number (first 4 bytes) - https://en.wikipedia.org/wiki/List_of_file_signatures
defmodule MagicNumber do
def extract_magic_number(<<byte :: size(32), _rest :: binary>>) do
Integer.to_string(byte, 16)
|> String.split(~r/.{2}/, include_captures: true, trim: true)
|> Enum.map(fn n -> "0x#{n}" end)
end
end
# Usage:
content = File.read!(path)
MagicNumber.extract_magic_number(content)
# Output (png file):
["0x89", "0x50", "0x4E", "0x47"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment