Skip to content

Instantly share code, notes, and snippets.

@takkkun
Created December 26, 2009 15:15
Show Gist options
  • Save takkkun/263965 to your computer and use it in GitHub Desktop.
Save takkkun/263965 to your computer and use it in GitHub Desktop.
#!/usr/bin/env escript
%% -*- erlang -*-
main(_) ->
io:format("~p~n", [hex_to_binary("180ff")]),
io:format("~p~n", [integer_to_binary(16#180ff)]).
hex_to_binary(Hex) ->
fold(fun
([L, U|H]) -> {char_to_integer(U) bsl 4 bor char_to_integer(L), H};
([L]) -> {char_to_integer(L), []};
([]) -> ok
end, lists:reverse(Hex)).
integer_to_binary(Integer) ->
fold(fun
(0) -> ok;
(I) -> {I band 16#ff, I bsr 8}
end, Integer).
fold(Fun, Input) ->
fold(Fun, Input, <<>>).
fold(Fun, Input, Binary) ->
case Fun(Input) of
{Byte, NextInput} -> fold(Fun, NextInput, <<Byte/integer, Binary/binary>>);
_ -> Binary
end.
char_to_integer(Char) when $0 =< Char, Char =< $9 ->
Char - $0;
char_to_integer(Char) when $a =< Char, Char =< $f ->
10 + Char - $a.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment