Skip to content

Instantly share code, notes, and snippets.

@kostiushkin
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save kostiushkin/8823074 to your computer and use it in GitHub Desktop.

Select an option

Save kostiushkin/8823074 to your computer and use it in GitHub Desktop.
-module(binary).
%% API
-export([binary_to_hexstring/1]).
-export([hexstring_to_binary/1]).
%% API
binary_to_hexstring(Bin) when is_binary(Bin) ->
bytelist_to_hexstring(binary_to_list(Bin)).
hexstring_to_binary(String) when is_list(String) ->
list_to_binary(hexstring_to_bytelist(String)).
%% internal
bytelist_to_hexstring([H|T]) when H < 256 ->
[hex_to_hexchar(H div 16), hex_to_hexchar(H rem 16)|bytelist_to_hexstring(T)];
bytelist_to_hexstring([]) ->
[].
hexstring_to_bytelist([X,Y|T]) ->
[hexchar_to_hex(X)*16 + hexchar_to_hex(Y)|hexstring_to_bytelist(T)];
hexstring_to_bytelist([]) ->
[].
hex_to_hexchar(N) when N < 10 ->
$0+N;
hex_to_hexchar(N) when N >= 10, N < 16 ->
$a+(N-10).
hexchar_to_hex(C) when $0 =< C, C =< $9 ->
C - $0;
hexchar_to_hex(C) when $A =< C, C =< $F ->
C - $A + 10;
hexchar_to_hex(C) when $a =< C, C =< $f ->
C - $a + 10.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment