Tuesday 2 October 2012

Binary, Hex, Octal and Decimal Conversion Under Linux

Base conversions are easy with linux CLI. No need of fancy GUI-based calculator to perform base conversions when there is our favorite linux terminal.

We will be using bc, a calculator language that supports arbitrary precision numbers with interactive execution of statements. We will exploit the pipelining feature of shell and will let the bc process our query to convert the numbers from one base to other.

From binary to decimal

The syntax is obvious and we will follow the similar syntax for all the conversions. In this first example, we are converting the binary number 1101101 from input base binary to decimal(obase defaults to decimal unless specified).

samar@samar-Techgaun:~$ echo "ibase=2;1101101" | bc
109


From octal to decimal

samar@samar-Techgaun:~$ echo "ibase=8;1101101" | bc
295489


From Hexadecimal to decimal

samar@samar-Techgaun:~$ echo "ibase=16;A1F3DF" | bc
10613727


From N-base to decimal

All you need to do is provide the appropriate ibase value (eg. ibase=4 for 4-base to decimal conversion).

samar@samar-Techgaun:~$ echo "ibase=16;A1F3DF" | bc
10613727


As seen in all the examples above, the conversion to decimal numbers does not require you to specify the obase as obase defaults to decimal. The same thing applies for ibase i.e. ibase defaults to decimal base by default as seen in the examples below.

Now lets try some conversion with decimal numbers as the input base.

From decimal to binary

samar@samar-Techgaun:~$ echo "obase=2;109" | bc
1101101


From decimal to octal

samar@samar-Techgaun:~$ echo "obase=8;295489" | bc
1101101


From decimal to hexadecimal

samar@samar-Techgaun:~$ echo "obase=16;10613727" | bc
A1F3DF


From decimal to N-base

All you need to do is provide the appropriate obase value (eg. obase=4 for decimal to 4-base conversion).

samar@samar-Techgaun:~$ echo "obase=4;121" | bc
1321


Below are few more examples of base conversions to clarify the use of the command.

From binary to octal

samar@samar-Techgaun:~$ echo "ibase=2;obase=8;1111" | bc
17


From hexadecimal to binary

samar@samar-Techgaun:~$ echo "ibase=16;obase=2;AFBE" | bc
1010111110111110


I hope this is helpful ;-)