Monday, April 23, 2012

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

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:
F
You need to set obase before ibase; otherwise you may get unexpected results:
echo "obase=16; ibase=8; 054253" | bc
Sample outputs:
58AB
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:
83B5

Printf command example

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

No comments:

Post a Comment