#!/bin/sh
# Basepak v1.1 - GNU General Public License - (c)1997 Toby Reed
# Convert between all combinations of hex, decimal, octal and binary

awk_printf() {
echo $2|$AWK '{printf("'$1'\n",$1)}'	# Awk Printf() routine
}

bp_bin2dec() {
for B in $BASE10;do {
C=$[$C+1];[ `echo $Y|cut -c$C` = 1 ]&&{ X=$[$X+$B]; }; };done
}

bp_bin2hex() {
for B in $BASE10;do {
C=$[$C+1];[ `echo $Y|cut -c$C` = 1 ]&&{ X=$[$X+$B]; }; };done
X=`$PRINTF %x $X`
}

bp_bin2oct() {
for B in $BASE8;do {
C=$[$C+1];[ `echo $Y|cut -c$C` = 1 ]&&{ X=$[$X+$B]; }; };done
}

bp_dec2bin() {
X=;for B in $BASE10;do {
C=0;[ $[$Y-$B] -ge 0 ]&&{ C=1;Y=$[$Y-$B]; };X=$X$C; };done
}

bp_dec2hex() {
X=`$PRINTF %x $Y`
}

bp_dec2oct() {
X=`$PRINTF %o $Y`
}

bp_hex2bin() {
X=;Y=$[0x$Y];for B in $BASE10;do {
C=0;[ $[$Y-$B] -ge 0 ]&&{ C=1;Y=$[$Y-$B]; };X=$X$C; };done
}

bp_hex2dec() {
X=$[0x$Y]
}

bp_hex2oct() {
X=`$PRINTF %o 0x$Y`
}

bp_oct2bin() {
unset X;B=400;until [ $B = 1 ]; do {
C=0;B=$[$B/2];[ $B = 5 ]&&B=4;[ $B = 50 ]&&B=40
[ $[$Y-$B] -ge 0 ]&&{ Y=$[$Y-$B];C=1; };X=$X$C };done
}

bp_oct2dec() {
X=`$PRINTF %d 0$Y`
}

bp_oct2hex() {
X=`$PRINTF %x 0$Y`
}

bp_basepak() {
cat << EOF
basepak v1.1 - (c)1997 Toby Reed <toby@eskimo.com>
Freely distributable under the terms of the GNU General Public License.

Convert between all combinations of hex, decimal, octal and binary.

Usage: bin2dec|bin2hex|bin2oct|dec2bin|dec2hex|dec2oct|hex2bin|hex2dec|
       hex2oct|oct2bin|oct2dec|oct2hex [number]

       basepak xxx2xxx [number]

Numbers are in the format of xxxxxxxx (binary), [xx]x (decimal), xx (hex)
and [xx]x (octal). They do NOT need to be prefixed with 0x, 0X or 0. The
xxx2xxx is one of the names listed above, such as bin2dec.
EOF
exit 1
}

AWK=awk				# Path to awk/gawk
PRINTF=printf			# Default - use GNU printf command
#PRINTF=awk_printf		# Uncomment if you don't have "printf" command

### No user-servicable parts beyond this line ###
X=0;Y=$1;Z=0;P=`basename $0>&/dev/null||echo $0`	# <-- Auto-detect
[ -z $Y ]&&Y=00000000					#   crappy system
[ $# = 2 ]&&{ P=$1;Y=$2;shift; }
BASE8="200 100 40 20 10 4 2 1"	# Base 8 additive equalities of binary
BASE10="128 64 32 16 8 4 2 1"	# Base 10 additive equalities of binary
PROGS="bin2dec bin2hex bin2oct dec2bin dec2hex dec2oct hex2bin hex2dec \
hex2oct oct2bin oct2dec oct2hex basepak"	# Valid xxx2xxx programs
for B in $PROGS; do { [ $B = $P ]&&{ Z=1;bp_$P; }; };done
[ $Z = 1 ]||{ echo "basepak: \"$P\" is an unknown basepak program!";exit 0; }
echo $X
exit 0

# Released v1.0 on 11-03-97
# Released v1.1 on 11-03-97
