Stratus3D
Stratus3D

Reputation: 4906

Convert base 2 number in a binary to an Erlang integer

Say I have a number like represented in a binary notation like this:

<<0:1, 0:1, 0:1, 0:1, 0:1, 1:1, 1:1, 1:1>>

This is binary notation for the number 7, evaluating this in the shell even yields 7:

<<7>>

How would I covert this binary to an Erlang integer? I can convert the binary to a list, and grab the single integer value in it, but this won't work large numbers that require multiple bytes, since the list will contain an item for each byte in the binary.

Upvotes: 3

Views: 1749

Answers (3)

Dogbert
Dogbert

Reputation: 222040

If you know you'll only have binaries and not bitstrings, i.e. the number of bytes will be a multiple of 8, you can use binary:decode_unsigned/1:

1> binary:decode_unsigned(<<0:1, 0:1, 0:1, 0:1, 0:1, 1:1, 1:1, 1:1>>).
7
2> binary:decode_unsigned(<<1:8, 0:1, 0:1, 0:1, 0:1, 0:1, 1:1, 1:1, 1:1>>).
263
3> binary:decode_unsigned(<<0:1, 0:1, 0:1, 0:1, 0:1, 1:1, 1:1, 1:1, 0:1, 0:1, 0:1, 0:1, 0:1, 1:1, 1:1, 1:1>>).
1799

Upvotes: 3

Steve Vinoski
Steve Vinoski

Reputation: 20004

One way is to use a binary comprehension to convert each bit individually to its character equivalent by adding $0, and then pass the resulting binary to binary_to_integer/2 to convert it, specifying its numeric base as 2:

1> binary_to_integer(<< <<(X+$0)>> || <<X:1>> <= <<0:1, 0:1, 0:1, 0:1, 0:1, 1:1, 1:1, 1:1>> >>, 2).
7
2> binary_to_integer(<< <<(X+$0)>> || <<X:1>> <= <<0:1, 0:1, 0:1, 0:1, 0:1, 1:1, 1:1, 1:1, 0:4, 1:1, 0:1, 1:1, 0:1>> >>, 2).
1802

The second example shows a longer binary that holds a value of hexadecimal 16#70A, or binary 2#11100001010, both of which are equivalent to the decimal value 1802.

Upvotes: 1

legoscia
legoscia

Reputation: 41527

Use pattern matching:

Bin = <<0:1, 0:1, 0:1, 0:1, 0:1, 1:1, 1:1, 1:1>>,
Size = bit_size(Bin),
<<X:Size>> = Bin.

After that, the variable X contains the integer 7. This works regardless of how many bits the binary contains.


In case you were wondering, it is in fact necessary to bind the bit size to the variable Size before matching. From the section on Bit Syntax Expressions of the Erlang Reference Manual:

Used in a bit string construction, Size is an expression that is to evaluate to an integer.

Used in a bit string matching, Size must be an integer, or a variable bound to an integer.

Upvotes: 6

Related Questions