Guest User

Untitled

a guest
Apr 6th, 2021
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. -module(binary).
  2. -export([encode_hex/1, decode_hex/1]).
  3.  
  4. encode_hex(Bin) when is_binary(Bin) ->
  5. encode_hex(Bin, <<>>).
  6.  
  7. encode_hex(<<>>, Acc) ->
  8. Acc;
  9. encode_hex(<<A0:4, B0:4, Rest/binary>>, Acc) ->
  10. A = encode_hex_digit(A0),
  11. B = encode_hex_digit(B0),
  12. encode_hex(Rest, <<Acc/binary, A, B>>).
  13.  
  14. encode_hex_digit(Char) when Char =< 9 ->
  15. Char + $0;
  16. encode_hex_digit(Char) when Char =< 15 ->
  17. Char + $A - 10.
  18.  
  19. decode_hex(Bin) when is_binary(Bin) ->
  20. decode_hex(Bin, <<>>).
  21.  
  22. decode_hex(<<>>, Acc) ->
  23. Acc;
  24. decode_hex(<<A0:8, B0:8, Rest/binary>>, Acc) ->
  25. A = decode_hex_char(A0),
  26. B = decode_hex_char(B0),
  27. decode_hex(Rest, <<Acc/binary, A:4, B:4>>).
  28.  
  29. decode_hex_char(Char) when Char >= $a, Char =< $f ->
  30. Char - $a + 10;
  31. decode_hex_char(Char) when Char >= $A, Char =< $F ->
  32. Char - $A + 10;
  33. decode_hex_char(Char) when Char >= $0, Char =< $9 ->
  34. Char - $0.
  35.  
Advertisement
Add Comment
Please, Sign In to add comment