integer to binary
Matthias Lang
matthias@REDACTED
Fri Oct 7 12:44:06 CEST 2005
chandru writes:
> I want to convert an integer to a binary without having to
> guess/figure-out how many bytes are required to fit that integer.
> There doesn't seem to be a way to do this with the bit syntax.
>
> 11> <<12345678901:40>>.
> <<2,223,220,28,53>>
>
> 12> <<12345678901:48>>.
> <<0,2,223,220,28,53>>
>
> In the example above, the integer will fit in 5 bytes but I can't
> think of a way to specify this without trial and error. Any
> suggestions?
If having the binary represent the integer in "the usual way" isn't a
requirement, then you can always do
1> term_to_binary(1234567890).
<<131,110,4,0,210,2,150,73>>
and if you don't mind being tripped up by the odd rounding problem,
there's always
Bits = math:log(My_integer) / math:log(2)
efficiency is probably not that great either.
Matthias
More information about the erlang-questions
mailing list