Skip to content

Instantly share code, notes, and snippets.

@keymone keymone/gist:78790
Created Mar 13, 2009

Embed
What would you like to do?
-module(base32).
-export([encode/1, decode/1]).
encode(Binary) ->
encode(Binary, <<>>).
encode(<<>>, To) -> To;
encode(<<B:1>>, To) -> <<To/binary, (symbol(B)), "====">>;
encode(<<B:2>>, To) -> <<To/binary, (symbol(B)), "=">>;
encode(<<B:3>>, To) -> <<To/binary, (symbol(B)), "=======">>;
encode(<<B:4>>, To) -> <<To/binary, (symbol(B)), "===">>;
encode(<<B:5/integer, Rest/bitstring>>, To) ->
encode(Rest, <<To/binary, (symbol(B)):8/integer>>).
decode(Binary) ->
decode(Binary, <<>>).
decode(<<>>, To) -> To;
decode(<<B:8, "====">>, To) -> <<To/binary, (B-1):1>>;
decode(<<B:8, "=">>, To) -> <<To/binary, (B-1):2>>;
decode(<<B:8, "=======">>, To) -> <<To/binary, (B-1):3>>;
decode(<<B:8, "===">>, To) -> <<To/binary, (B-1):4>>;
decode(<<B:8, Rest/binary>>, To) ->
decode(Rest, <<To/binary, (value(B)):5>>).
symbol(B) when B >= 0 andalso B =< 25 -> $A + B;
symbol(B) when B < 32 -> $2 + B - 26.
value(B) when B >= $A andalso B =< $Z -> B - $A;
value(B) when B >= $2 andalso B =< $9 -> B + 26 - $2.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.