Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(binary).
- -export([encode_hex/1, decode_hex/1]).
- encode_hex(Bin) when is_binary(Bin) ->
- encode_hex(Bin, <<>>).
- encode_hex(<<>>, Acc) ->
- Acc;
- encode_hex(<<A0:4, B0:4, Rest/binary>>, Acc) ->
- A = encode_hex_digit(A0),
- B = encode_hex_digit(B0),
- encode_hex(Rest, <<Acc/binary, A, B>>).
- encode_hex_digit(Char) when Char =< 9 ->
- Char + $0;
- encode_hex_digit(Char) when Char =< 15 ->
- Char + $A - 10.
- decode_hex(Bin) when is_binary(Bin) ->
- decode_hex(Bin, <<>>).
- decode_hex(<<>>, Acc) ->
- Acc;
- decode_hex(<<A0:8, B0:8, Rest/binary>>, Acc) ->
- A = decode_hex_char(A0),
- B = decode_hex_char(B0),
- decode_hex(Rest, <<Acc/binary, A:4, B:4>>).
- decode_hex_char(Char) when Char >= $a, Char =< $f ->
- Char - $a + 10;
- decode_hex_char(Char) when Char >= $A, Char =< $F ->
- Char - $A + 10;
- decode_hex_char(Char) when Char >= $0, Char =< $9 ->
- Char - $0.
Advertisement
Add Comment
Please, Sign In to add comment