Linux / UNIX: bc Convert Octal To Hexadecimal or Vise Versa

Posted on in Categories last updated November 23, 2010

How do I convert from octal to hex number using bc UNIX / Linux command line utility?

The octal numeral system is a base 8 numeral system. It uses the numerals 0 through 7. You need to use the following bc syntax to covert number:

echo "obase=16; ibase=8; octal-number-here" | bc
echo "obase=16; ibase=8; 17" | bc

Sample outputs:


You need to set obase before ibase; otherwise you may get unexpected results:

echo "obase=16; ibase=8; 054253" | bc

Sample outputs:


This is wrong (yes, bc isn’t smart enough to figure this out on its own; so make sure you set obase before ibase):

echo "ibase=8; obase=16; 054253" | bc

Sample outputs:


Printf command example

You can also use the printf command as follows:
$ printf "%x\n" 0306
Sample output:


Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Leave a Comment