Reputation: 4906
I can convert an integer to a binary easily in Erlang:
integer_to_binary(11, 10).
The bits in the returned binary are in this case contains these bits:
0011000100110001
I'd like write a function to generate a binary containing the binary-notation of the number passed in. That is, the number eleven would look like this in bits:
1011
Is there an easy way to do this in Erlang?
Upvotes: 1
Views: 327
Reputation: 222040
To convert an arbitrary sized unsigned integer to a binary consisting of the bytes in the integer, you can use binary:encode_unsigned/1
or binary:encode_unsigned/2
.
1> binary:encode_unsigned(11).
<<"\v">>
2> binary:encode_unsigned(11) == <<0:4, 1:1, 0:1, 1:1, 1:1>>.
true
binary:encode_unsigned/1
will store the bytes in big endian representation. To store the bytes in little endian, you can use binary:encode_unsigned/2
:
1> binary:encode_unsigned(123456789, little).
<<21,205,91,7>>
2> binary:encode_unsigned(123456789, big).
<<7,91,205,21>>
Upvotes: 2