Erlang Central

Converting Between Binary and Decimal

From ErlangCentral Wiki


You would like to display the binary representation of an integer, or the integer representation of a binary value. You might want to do this if you were displaying non-textual data, such as what you get from interacting with certain system programs and functions.


Use the io_lib:fread and io_lib:format built in functions. Each of these functions takes an optional radix specifier, which can be used to determine what number base to use for the output (or which base to use for conversion to a numerical value).

1> hd(io_lib:format("~.2B", [16])).
158> io_lib:fread("~2u", "0110001110"). 


Note that this recipe is not limited to binary numbers. We could just as easily have presented hexadecimal or octal versions:

1> hd(io_lib:format("~.16B", [16])).
2> {ok, Val, _} = io_lib:fread("~8u", "266").
3> hd(Val).

Note how Erlang displays the numeric value as a paragraph sign. This is another instance of Erlang treating strings as lists of integers -- lists of integers get treated as strings!

We can verify the value is correct be taking the head (hd) of the list to see that it is the value 266, as we expected.