Perform number base conversions and calculations.
Note: The script behaves differently, depending on the filename (the executable may still be the same file). The following hard-links ($ ln math.sh …) to the math.sh script provides the following shortcuts…

  • x2d (hex to decimal), x2o (hex to octal), x2b (hex to binary)
  • d2x (decimal to hex), d2o (decimal to octal), d2b (decimal to binary)
  • o2x (octal to hex), o2d (octal to decimal), o2b (octal to binary)
  • b2x (binary to hex), b2d (binary to decimal), b2o (binary to octal)

Example usage:
  $ d2x;  # (Interactive) decimal to hex conversions
  $ x2d a b c d e f 10/2
  $ echo ‘f+1 ff+2’ | x2d

#! /bin/sh
#  Synopsis:    Math.sh [-i inputbase] [-o outputbase] [math-expression | Number]  ...
#  Description: Math.sh performs base number conversions, and 'bc -l' calculations
#               Note1: Spaces should be avoided in math-expressions.  A space character in 
#                      an expression may be intepreted as a command line field separator.
#               Note2: Renaming or (hard/symbolic) ln'ing to the script alters the default input 
#                     and output base (ie: b2o,b2d,b2x, o2b,o2d,o2x, d2b,d2o,d2x, x2b,x2d,x2d)
#                                          (b=binary, o=octal, d=decimal, x=hexadecimal)
#  Example Usage: $ math.sh;  # Interactive decimal calculator
#                 $ math.sh '1.11111111^2'
#                 $ echo 'ff ff+1' | x2d 

obase=10
ibase=10
case $0 in
  *b2o) ibase=2;  obase=8;;
  *b2d) ibase=2;  obase=10;;
  *b2x) ibase=2;  obase=16;;
  *o2b) ibase=8;  obase=2;;
  *o2d) ibase=8;  obase=10;;
  *o2x) ibase=8;  obase=16;;
  *d2b) ibase=10; obase=2;;
  *d20) ibase=10; obase=8;;
  *d2x) ibase=10; obase=16;;
  *x2b) ibase=16; obase=2;;
  *x2o) ibase=16; obase=8;;
  *x2d) ibase=16; obase=10;;
  *[Mm]ath*)
        while getopts i:o: opt; do
                case "$opt" in
                  i) ibase=$OPTARG;;
                  o) obase=$OPTARG;;
                esac
        done
        shift `expr $OPTIND - 1`
        ;;
esac

{
echo "obase=$obase"
echo "ibase=$ibase"
if [ $# -eq 0 ]; then
        cat
else
        echo "$*"
fi | tr 'a-f ' 'A-F\n' 
} | bc -l