view · edit · attach · print · history

The contents of this website are Copyright (c)2004 by Brian Manning <brian at antlinux dot com>. Please do not reuse any of the content on this website without permission from the author.

Using Perl

Usage:

 perl -e "print hex(hex # with no leading '0x')"

Example:

 perl -e "print hex(311) . qq(\n);"
 785

Another way to do it in Perl is to use printf. Example:

 perl -e "printf(qq(%x\n), 785);"

The extra \n string in the quoted string qq() is a newline character.

To go from hex to decimal, use the %u primitive to printf():

 perl -e "printf(qq(%u\n), 0x311);"

See the sprintf perldoc page for a list of primitives that can be used to convert from one number base to another.

Using 'bash'

(Thanks to choroba (at) matfyz.cz for the suggestion)

bash uses the same primitives and functions as Perl does:

 $ printf '%x\n' 785
 311
 $ printf '%x\n' 255
 ff
 $ printf '%d\n' 0x311
 785
 $ printf '%d\n' 0xff
 255

Using 'bc'

Need to convert hexadecimal numbers to decimal (changing ibase)? Try this:

 [observer][root grub]$ echo "ibase=16;311" | bc
 785

ibase is the input base (here we're changing it to base 16, or hexadecimal), and 311 in the bc command is the hexadecimal number you want to convert to decimal.

The default ibase and obase in bc defaults to base 10, or decimal.

How about from decimal to hexadecimal (changing obase)?

 [observer][root grub]$ echo "obase=16;77" | bc
 4D

This version of the bc command works the opposite way, changing the decimal number (ibase=10) to hexadecimal (obase=16).

REMEMBER: if you are converting from hex to base 10 using bc, you'll need to type any hex letters in UPPERCASE, bc chokes on lowercase letters.

view · edit · attach · print · history
Page last modified on May 11, 2007, at 12:38 PM