Search code examples
erlangdecodeencodeieee-754

Decode / Encoded IEEE 754 float value from raw data with Erlang?


New to Erlang here... I'm needing to extract an IEEE 754 float value from raw data in a List. E.g. Decode: [42,91,0,0] should equal 72.5 and also convert a float to a list Encode: 72.5 should convert to [42,91,0,0] Are there any libraries that support these operations? What is best practice? Thanks in advance.


Solution

  • For decoding, you can convert the list to a binary, then extract the float from the binary (note that the original list values in your question are hexadecimal, which is why they are prefixed with 16# in the list below):

    1> <<V:32/float>> = list_to_binary([16#42, 16#91, 0, 0]).
    <<66,145,0,0>>
    2> V.
    72.5
    

    For encoding, do the reverse: insert the float value into a binary, then convert that to a list:

    3> binary_to_list(<<V:32/float>>).
    [66,145,0,0]