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