16

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)).
2240
  • 1,547
  • 2
  • 12
  • 30
BAR
  • 15,909
  • 27
  • 97
  • 185
  • 2
    Shouldn't it be list_to_binary(integer_to_list(Int))? – hdima Oct 25 '10 at 08:04
  • I think what he meant is that generating fully-functional-string in erlang takes too much mem (becuase its linked list of characters, so with each letter it consumes extra 32-bit or 64-bit for pointer to next char in string) – test30 Jun 14 '15 at 01:09
  • I highly doubt the erlang devs made strings a linked list of chars. I have not checked myself but i cant imagine such an inefficient use of linked list in production. – BAR Jun 14 '15 at 02:14

3 Answers3

32

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>>
hdima
  • 3,627
  • 1
  • 19
  • 19
19

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

Andy Till
  • 3,371
  • 2
  • 18
  • 23
5

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.

Damodharan R
  • 1,497
  • 7
  • 10
  • Good Idea, but what if I don't know. Isn't there a binary option without the colon to do it. I tried _ didn't work. – BAR Oct 24 '10 at 23:01
  • You can always do the conversion in steps. (A rem 4294967296) for each 32 bits and loop. – Daniel Luna Oct 25 '10 at 16:46