Erlang Central

Converting Between Binary and Decimal

Revision as of 23:25, 3 September 2006 by Bfulgham (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Problem

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.

Solution

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])).
"10000"
158> io_lib:fread("~2u", "0110001110"). 
{ok,[398],[]}

Discussion

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])).
"10"
2> {ok, Val, _} = io_lib:fread("~8u", "266").
{ok,"¶",[]}
3> hd(Val).
266

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.