:
# @(#) cbase.ksh 1.1 94/01/01
# 11/08/90 john h. dubois iii (john@armory.com)
# 91/02/13 cleaned up
# 91/04/29 changed incorrect reference to xbase() to cbase()
# 93/07/12 Added -o and -O options and ksh input bases.
# 94/01/01 Changed [oO] to [rR], added bBoOxX options.

alias istrue="test 0 -ne"
alias isfalse="test 0 -eq"

# cbase: convert C-style constants to decimal numbers

# convert hex (0xnnn and 0Xnnn), octal (0nnn), and decimal C constants
# to decimal & print
cbase() {
    typeset -i$obase d
    out=
    while [ $# -gt 0 ]; do
	case $1 in
	    0[xX]*([0-9a-fA-F]) ) d=16#${1#0[xX]};;
	    0*([0-7]) ) d=8#$1;;
	    [1-9]*([0-9]) ) d=$1;;
	    +([0-9])#+([0-9]) ) d=$1;;
	    *) echo "bad number: $1"; shift; continue;;
	esac
	istrue nobase && out="$out ${d#+([0-9])#}" || out="$out $d"
	shift
    done
    echo $out
}

typeset -i obase=10 nobase=0

name=${0##*/}
Usage="Usage: $name [-hbBoOxX] [-[rR]<output-base>] <integer value> ..."

while getopts :hr:R:bBoOxX opt; do
    case $opt in
    h)
    echo \
"cbase: convert integers between bases.
$Usage
Octal, decimal, and hexadecimal values may be given using C notation (nnn,
0nnn, and 0xnnn  respectively).  A value may be entered in any base
between 2 and 2^32-1 using ksh notation (base#value, e.g. 7#33 to enter a
value in base 7).
If no numbers are given on the command line, they are read from the input
until end of file is reached.
Options:
-h: Print this help.
-r<base>: Change the output base (radix) to <base>; must be between 2 and 36.
-b: Change the output base to 2 (binary).
-o: Change the output base to 8 (octal).
-x: Change the output base to 16 (hex).
-R<base>, -B, -O, -X: Like the lower case options, except that the output
    will not include base specifiers."
	exit 0
	;;
    [rR])
	obase=$OPTARG || exit 1
	;;
    [bB])
	obase=2
	;;
    [oO])
	obase=8
	;;
    [xX])
	obase=16
	;;
    +?)
	echo "$name: options should not be preceded by a '+'."
	exit 1
	;;
    ?) 
	echo "$name: $OPTARG: bad option.  Use -h for help."
	exit 1
	;;
    esac
    [[ $opt = [A-Z] ]] && nobase=1
done
 
# remove args that were options
let OPTIND=OPTIND-1
shift $OPTIND

if [ $# -gt 0 ]; then
    cbase $*
else
    while read line; do
    cbase $line
    done
fi
