Erlang Central

Converting Between Octal and Hex

Revision as of 14:54, 21 November 2006 by (Talk)


You want to convert a string (e.g., "0x55" or "0755") containing an octal or hexadecimal number to the correct number.


Use the io_lib:fread and io_lib:fwrite built in functions.

1> io_lib:fread("~16u", "55").
% Note:  "U" is ASCII 85, so the conversion produces the
% correct integer value:
2> $U.
3> io_lib:fread("~8u", "755").

The io_lib:fread function takes an optional radix (which must be an exact integer, from 2 to 36). If not supplied, it defaults to decimal.

You can provide specific formatting for numbers using the io_lib:format or io:fwrite functions (which use the same syntax): 4> io:fwrite("~.16B\n", [123]). 7B

Note that the radix and numbers may be upper or lower case.

Here's an example that accepts a number in either decimal, octal, or hex, and prints that number in all three bases. It uses the oct function to convert from octal and hexadecimal if the input began with a 0. It then uses printf to convert back into hex, octal, and decimal as needed.

convert(Str) ->
    {ok, [Num], _ } = io_lib:fread("~u", Str),
    io_lib:format("decimal=~B, hex=~.16B, octal=~.8B",
        [Num, Num, Num]).

5> io:fwrite("~s\n", [cookbook:convert("123")]).
decimal=123, hex=7B, octal=173

The following code converts Unix file permissions. They're always given in octal, so we assume base 8:

fp_convert(Str) ->
  {ok, [Num], _ } = io_lib:fread("~8u", Str),
  io:fwrite("The decimal value is ~B~n", [Num]).

6> cookbook:fp_convert("777").
The decimal value is 511