Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- defmodule Binary do
- def encode_hex(bin) when is_binary(bin) do
- encode_hex(bin, "")
- end
- defp encode_hex("", acc), do: acc
- defp encode_hex(<<a::4, b::4, rest::binary>>, acc) do
- a = encode_hex_digit(a)
- b = encode_hex_digit(b)
- encode_hex(rest, <<acc::binary, a, b>>)
- end
- defp encode_hex_digit(char) when char <= 9, do: char + ?0
- defp encode_hex_digit(char) when char <= 15, do: char + ?a - 10
- def decode_hex(bin) when is_binary(bin) do
- decode_hex(Bin, "")
- end
- def decode_hex("", acc), do: acc
- defp decode_hex(<<a::8, b::8, rest::binary>>, Acc) do
- a = decode_hex_char(a)
- b = decode_hex_char(b)
- decode_hex(rest, <<acc::binary, a::4, b::4>>)
- end
- defp decode_hex_char(char) when char in ?a..?f, do: char - ?a + 10
- defp decode_hex_char(char) when char in ?A..?F, do: char - ?A + 10
- defp decode_hex_char(char) when char in ?A..?F, do: char - ?0
- end
Advertisement
Add Comment
Please, Sign In to add comment