Skip to content

Instantly share code, notes, and snippets.

@mks-m
Created March 13, 2009 21:51
Show Gist options
  • Save mks-m/78790 to your computer and use it in GitHub Desktop.
Save mks-m/78790 to your computer and use it in GitHub Desktop.
-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