integer to binary

Bjorn Gustavsson bjorn@REDACTED
Fri Oct 7 14:44:02 CEST 2005


Actually, as Mattias Lang pointed out in a email to me, the guard test
is unecessary.

So here is a better version of the code, with a better name and validity
tests so that you'll know if you pass it values it isn't designed to handle:

unsigned_to_bin(I) when is_integer(I), I >= 0 ->
    unsigned_to_bin(I, []).

unsigned_to_bin(0, Acc) ->
    list_to_binary(Acc);
unsigned_to_bin(N, Acc) ->
    unsigned_to_bin(N bsr 8, [N band 16#ff|Acc]).

/Bjorn

Bjorn Gustavsson <bjorn@REDACTED> writes:

> It is actually easier not to use the bit syntax.
> For positive numbers the following function will do the trick:
> 
> int_to_bin(I) ->
>     int_to_bin(I, []).
> 
> int_to_bin(0, [B|Acc]) when B < 256 ->
>     list_to_binary([B|Acc]);
> int_to_bin(N, Acc) ->
>     int_to_bin(N bsr 8, [N band 16#ff|Acc]).
> 
> /Björn
> 
> chandru <chandrashekhar.mullaparthi@REDACTED> writes:
> 
> > Hi,
> > 
> > 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? I can write a function which will figure out how many
> > bytes are required but it'll be nice to have a built-in way of doing
> > it.
> > 
> > cheers
> > Chandru
> > 
> 
> -- 
> Björn Gustavsson, Erlang/OTP, Ericsson AB
> 

-- 
Björn Gustavsson, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list