BAR
BAR

Reputation: 17071

How do I convert an integer to a binary in Erlang?

I am trying to make an integer into a binary:

543 = <<"543">>

How can I do this without

integer_to_list(list_to_binary(K)).

Upvotes: 16

Views: 20513

Answers (4)

Fylke
Fylke

Reputation: 1836

I found this question because I wanted the "print representation" of a binary written as an integer. This is how you do that:

1> integer_to_list(543, 2).
"1000011111"

The second argument is the base you want, and it accepts all the way up to 36 (go to Wikipedia and read about base36 encoding now).

Upvotes: 0

Andy Till
Andy Till

Reputation: 3511

For current readers, this is now implemented in R16, see http://erlang.org/doc/man/erlang.html#integer_to_binary-1

Upvotes: 19

hdima
hdima

Reputation: 3637

If you want to convert 543 to <<"543">> I don't think you can find something faster than:

1> list_to_binary(integer_to_list(543)).
<<"543">>

Because in this case both functions implemented in C.

If you want to convert integer to the smallest possible binary representation you can use binary:encode_unsigned function from the new binary module like this:

1> binary:encode_unsigned(543).
<<2,31>>
2> binary:encode_unsigned(543, little).
<<31,2>>

Upvotes: 32

Damodharan R
Damodharan R

Reputation: 1507

You can try something like

6> A = 12345.                       
12345
7> B = <<A:32>>.
<<0,0,48,57>>

But this requires you to know the maximum number of bits in advance.

Upvotes: 5

Related Questions