Convert base 2 number in a binary to an Erlang integer
binary, erlang, numbers, radix
Solution
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.
Problem
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.