Skip to content

Instantly share code, notes, and snippets.

@h4cc
Created April 22, 2021 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h4cc/e0839d0cd7eb89065c14a487c4d5fcdc to your computer and use it in GitHub Desktop.
Save h4cc/e0839d0cd7eb89065c14a487c4d5fcdc to your computer and use it in GitHub Desktop.
defmodule MyBinaryParser do
# Parsing a 2 byte binary to float16
# according to: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
# Float16 is build in OTP 24.
def parse_float16(<<sign::1, exponent::5, significand::10>>) do
case {sign, exponent, significand} do
{0b0, 0b00000, 0b0000000000} ->
0.0
{0b1, 0b00000, 0b0000000000} ->
-0.0
{sign, 0b00000, significand} ->
# Subnormal numbers
:math.pow(-1, sign) * :math.pow(2, -14) * (0 + (significand / 1024))
{0b0, 0b11111, 0b0000000000} ->
:infinity_positive
{0b1, 0b11111, 0b0000000000} ->
:infinity_negative
{_, 0b11111, _} ->
:nan
{sign, exponent, significand} ->
# Normalized values
:math.pow(-1, sign) * :math.pow(2, exponent-15) * (1 + (significand / 1024))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment