#!/bin/sh
#vim:setsw=4ts=4et:
help()
{
cat<
b2h--convertbinarytodecimal
USAGE:b2h[-h]binarynum
OPTIONS:-hhelptext
EXAMPLE:b2h111010
willreturn58
HELP
exit0
}
error()
{
#printanerrorandexit
echo"$1"
exit1
}
lastchar()
{
#returnthelastcharacterofastringin$rval
if[-z"$1"];then
#emptystring
rval=""
return
fi
#wcputssomespacebehindtheoutputthisiswhyweneedsed:
numofchar=`echo-n"$1"|wc-c|sed's///g'`
#nowcutoutthelastchar
rval=`echo-n"$1"|cut-b$numofchar`
}
chop()
{
#removethelastcharacterinstringandreturnitin$rval
if[-z"$1"];then
#emptystring
rval=""
return
fi
#wcputssomespacebehindtheoutputthisiswhyweneedsed:
numofchar=`echo-n"$1"|wc-c|sed's///g'`
if["$numofchar"="1"];then
#onlyonecharinstring
rval=""
return
fi
numofcharminus1=`expr$numofchar"-"1`
#nowcutallbutthelastchar:
rval=`echo-n"$1"|cut-b0-${numofcharminus1}`
}
while[-n"$1"];do
case$1in
-h)help;shift1;;#functionhelpiscalled
--)shift;break;;#endofoptions
-*)error"error:nosuchoption$1.-hforhelp";;
*)break;;
esac
done
#Themainprogram
sum=0
weight=1
#oneargmustbegiven:
[-z"$1"]&&help
binnum="$1"
binnumorig="$1"
while[-n"$binnum"];do
lastchar"$binnum"
if["$rval"="1"];then
sum=`expr"$weight""+""$sum"`
fi
#removethelastpositionin$binnum
chop"$binnum"
binnum="$rval"
weight=`expr"$weight""*"2`
done
echo"binary$binnumorigisdecimal$sum"