e r l a n g : c o o k b o o k

/ Erlang.NumberConvOctHex

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Converting Between Octal and Hexadecimal

Problem

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

Solution

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

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

Discussion

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
ok

See Also

NumberRecipesConvertBinDec?

-- BrentAFulgham - 26 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: NumberRecipes
TopicOrder: 130

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest