Skip to content

Instantly share code, notes, and snippets.

@samrat
Created September 7, 2014 10:01
Show Gist options
  • Save samrat/8a4aa6d46b0dffb7bb1c to your computer and use it in GitHub Desktop.
Save samrat/8a4aa6d46b0dffb7bb1c to your computer and use it in GitHub Desktop.
Convert a binary representation to IEEE floats
%% K - number of bits to represent `exp`,
%% N - number of bits to represent `frac`.
%% | s | exp(k bits) | frac(n bits) |
make_float_converter(K, N) ->
Bias = math:pow(2, K-1) - 1,
Max_denom = math:pow(2, N),
Max_exp = round(math:pow(2, K) - 1),
fun(<<S:1, Exp:K, Frac:N>>) ->
case Exp of
0 -> E = 1 - Bias, % denormalized
M = Frac / Max_denom,
math:pow(-1, S) * M * math:pow(2, E);
Max_exp -> case Frac of % special cases
0 -> case S of
0 -> pos_infinity;
1 -> neg_infinity
end;
_ -> nan
end;
_ -> E = Exp - Bias, % normalized
M = 1 + (Frac / Max_denom),
math:pow(-1, S) * M * math:pow(2, E)
end
end.
%% Usage:
%% ======
%% F = ieee:make_float_converter(2,2).
%% F(<<2#01011>>).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment