« The Special Pig | Main | Revenge »

November 24, 2005

Hex Converter

There is a magic string that you feed to dc when you want to convert a hex number to a decimal:

echo "16 10 o i FF p" | dc

The idea is that you can convert any base 16 number to a decimal easily. Although the string looks arbitrary it is actually quite meaningful if I tell you that dc is an RPN calculator (more jargon). How about a step by step example (if you type this in, ignore the comments - lines that start with a '#' character):


# Start the program dc (probably /usr/bin/dc)
$ dc
# Add 16 to the stack (another bit of jargon)
16
# Add 10 to the stack (on top of the 16)
10
# Take the top stack value (10) for the output radix (i.e. base)
o
# Take the top stack value (16) for the input radix
i
# Chuck any old hex number onto the stack
DEADBEEF
# Print the top stack value out
p
3,735,928,559

Intelligent readers should be able to use the same method to convert decimal to binary.....

Posted by Ozguru at November 24, 2005 06:00 AM