Created
April 22, 2021 05:27
-
-
Save h4cc/e0839d0cd7eb89065c14a487c4d5fcdc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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