/src/encoding.erl

https://gitlab.com/unq-sd2016-s1-alvarez-dubor/collabory · Erlang · 44 lines · 27 code · 8 blank · 9 comment · 0 complexity · 8682b5ac03b79ea846d374e67a2863ae MD5 · raw file

  1. %%%-------------------------------------------------------------------
  2. %%% @author logain
  3. %%% @copyright (C) 2016, <COMPANY>
  4. %%% @doc
  5. %%%
  6. %%% @end
  7. %%% Created : 10. jul 2016 23:34
  8. %%%-------------------------------------------------------------------
  9. -module(encoding).
  10. -author("logain").
  11. %% API
  12. -export([tuple_to_token/1, token_to_tuple/1]).
  13. hex(N) when N < 10 ->
  14. $0+N;
  15. hex(N) when N >= 10, N < 16 ->
  16. $a+(N-10).
  17. int(C) when $0 =< C, C =< $9 ->
  18. C - $0;
  19. int(C) when $A =< C, C =< $F ->
  20. C - $A + 10;
  21. int(C) when $a =< C, C =< $f ->
  22. C - $a + 10.
  23. to_hex(N) when N < 256 ->
  24. [hex(N div 16), hex(N rem 16)].
  25. list_to_hexstr([]) ->
  26. [];
  27. list_to_hexstr([H|T]) ->
  28. to_hex(H) ++ list_to_hexstr(T).
  29. tuple_to_token(Touple) ->
  30. list_to_hexstr(binary_to_list(term_to_binary(Touple))).
  31. token_to_tuple(S) ->
  32. binary_to_term(list_to_binary(hexstr_to_list(S))).
  33. hexstr_to_list([X,Y|T]) ->
  34. [int(X)*16 + int(Y) | hexstr_to_list(T)];
  35. hexstr_to_list([]) ->
  36. [].