Erlang Central

Converting Between Octal and Hex

From ErlangCentral Wiki


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]).

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.

-export([convert/1, fp_convert/1]).

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

fp_convert/1 is defined below. Include it in the above file before compiling.

Sample usage:

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]).

Usage of it:

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