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

/ Erlang.NumberConvertBinDec

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 Binary and Decimal

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.

See Also

NumberRecipeConvOctHex?

-- BrentAFulgham - 23 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: NumberRecipes
TopicOrder: 040

 
 
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