**Convert Binary,HEX, Oct to decimal**

This is a small Shell tutorial on how to convert different bases to other bases.

Some times when working as system admin you require to convert different number systems to others. In this post we will see how to convert different number systems to others.

## Decimal to Binary

echo "obase=2; 23" | bc

**Output:**

**10111**

Let me explain above command. **obase** is a** special variable** in bc command which defines the output base value for a given number. There is one more special variable for bc command called** ibase** which defines input base value. In our example we did not mention ibase so by default it will take my input value as decimal value. So we feed **obase=2** and **decimal number 23** to bc command to convert decimal 23 in to binary number.

## Decimal to Octal number

echo "obase=8; 23" | bc

Decimal to Hex number

echo "obase=16; 23" | bc

Decimal to any base number

convert decimal number to base 4 number system

echo "obase=4; 23" | bc

How about convert to base 7?

echo "obase=7; 23" | bc

## Binary to decimal

echo "ibase=2; 11010101" | bc

## Oct to decimal

echo "ibase=8; 723" | bc

## Hex to decimal

echo "ibase=16; 23" | bc

## How about converting binary to Oct?

echo "ibase=2;obase=8 1010101" | bc

As given above we can convert any number system to any number systems

## Other ways to do base convertions

bc will convert from any base to any other base. There are some other tools which can do partially these conventions.

$(()) –can convert hex to decimal

example:

echo $((0x123))

**printf command can convert hex and oct to decimal**

**decimal to Octal**

printf "%on" 123

**decimal to Hex**

printf "%xn" 123

bng

Thank you for the helpful post, I can’t get all the commands to work on my Ubuntu 13.04 however:

~$ echo “ibase=2;obase=8 1010101″ | bc

(standard_in) 1: syntax error

~$ echo “ibase=16; 123abc” | bc

(standard_in) 1: syntax error

even though this works:

~$ echo “obase=2; 23″ | bc

10111

any idea, what got wrong?

Surendra Anne

it should work with out any issues. Can you try them with single quotes?

BNG

Single quotes make no difference in my shell, but I found out what is the problem:

~$ echo ‘ibase=2;obase=8 1010101;’ | bc

(standard_in) 1: syntax error

~$ echo ‘ibase=2;obase=8; 1010101′ | bc

125

I needed to add semicolon!

Cheers

BNG

Yet strangely, it seems to work only with numbers, not letters:

~$ echo “ibase=16;obase=10;123bdf” | bc

(standard_in) 1: syntax error

~$ echo “ibase=16;obase=10;bdf” | bc

0

~$ echo “ibase=16;obase=10;123″ | bc

123

RubyTuesdayDONO

very helpful! bc is such a great tool. thank you!