Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)).
like image 965
BAR Avatar asked Oct 24 '10 22:10

BAR


People also ask

How do you convert integer to binary representation?

To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order.

Is binary in Erlang?

Use a data structure called a binary to store large quantities of raw data. Binaries store data in a much more space efficient manner than in lists or tuples, and the runtime system is optimized for the efficient input and output of binaries.

How do you convert a number to binary in Java?

To convert decimal to binary, Java has a method “Integer. toBinaryString()”. The method returns a string representation of the integer argument as an unsigned integer in base 2.


1 Answers

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>>
like image 51
hdima Avatar answered Sep 29 '22 22:09

hdima