Search code examples
typesbinaryerlangdata-representation

Erlang binary representation for float & integer, discrepancy?


Got another Erlang binary representation query ('coz that's what I am reading about these days, and need for binary protocol implementation).

If I understand the type-specifier properly, then, for a "float" type value the 8 byte representation seems fine (this is on 64-bit Win7).

1> <<A1/binary>> = <<12.3214/float>>.
<<64,40,164,142,138,113,222,106>>

However what stumped me, was that the "integer" type value's binary representation.

2> <<A2/binary>> = <<32512/integer>>.
<<0>>
3> <<A3/binary>> = <<232512518/integer>>.
<<6>>
4> <<A5/binary>> = <<80/integer>>.
<<"P">>

Why are all of those represented in 1 byte ? Can someone please explain this ?


Solution

  • You're not converting Erlang terms to their binary representation. You're using the binary syntax to build binaries. Using integer will truncate them to fit into one byte:

    3> <<255/integer>>. % Under one byte
    <<"ÿ">>
    4> <<256/integer>>. % "Over" one byte
    <<0>>
    

    Try this:

    5> term_to_binary(32512).
    <<131,98,0,0,127,0>>
    6> term_to_binary(232512518).
    <<131,110,4,0,6,220,219,13>>
    7> term_to_binary(80).
    <<131,97,80>>
    

    131 is the version number, 97 is a small integer (8-bit), 98 is a big integer (32-bit), 110 (and 111) are for bignum integers. The rest is the data for the actual numbers.

    See the documentation for the Erlang binary term format for further info on what the bytes mean.