Hexadecimal
Definition
Hexadecimal is a counting system based on sixteen digits (0,1, 2, 3, 4, 5, 6, 7). To expand an hexadecimal number to decimal, multiply each digit in the number with the corresponding power of sixteen. The following shell script demonstrates this:
#!/bin/bash
# Take an hexadecimal number and output it's decimal version
hexadecimal=$1
length=`echo $hexadecimal | wc -c | tr -d " "`
power=1
while [ $length -gt 2 ]
do
power=$(( $power * 16 ))
length=$(( $length - 1 ))
done
decimal=0
while [ "%$hexadecimal%" != "%%" ]
do
digit=`echo $hexadecimal | cut -b 1`
echo -n "Hexadecimal = $hexadecimal, Digit = $digit, Power = $power, Value = "
value=$(( $digit * $power ))
echo $value
decimal=$(( $decimal + value ))
power=$(( $power / 16 ))
hexadecimal=`echo $hexadecimal | sed 's/^.//'`
done
echo ""
echo "Result = $decimal"
The following shell script example shows how to convert a decimal number to hexadecimal from first principles:
#!/bin/bash
# Take a decimal number and output it's hexadecimal
quotient=$1
while [ $quotient -ne 0 ]
do
remainder=$(( $quotient % 16 ))
hexadecimal="$remainder$hexadecimal"
quotient=$(( $quotient / 16 ))
done
echo $hexadecimal
References
Computer Engineering Hardware Design by M Morris Mano published by Prentice Hall 1988
See also
Binary
Octal
Decimal
Entry history
Entry created: Thu Mar 20 15:20:12 EST 2003
Entry owner: Michael Still (mikal@stillhq.com)
Status: Finalized