dotfiles

My personal shell configs and stuff
git clone git://git.alex.balgavy.eu/dotfiles.git
Log | Files | Refs | Submodules | README | LICENSE

base (1629B)


      1 #!/bin/sh
      2 # Simple base converter
      3 # base [-x|-d|-o|-b] [0x|0d|0o|0b|]NUM
      4 command -v bc >/dev/null 2>&1 || { printf "bc not installed.\n" && exit 1; }
      5 
      6 usage() {
      7   printf "Usage: %s [options] num" "$0"
      8 }
      9 [ $# -ge 1 ] || { usage && exit 1; }
     10 
     11 PARAMS=""
     12 
     13 while [ $(($#)) -ne 0 ]; do
     14   case "$1" in
     15     -x|--hex)
     16       obase=16
     17       baseprefix='0x'
     18       shift
     19       ;;
     20     -d|--decimal)
     21       obase=10
     22       baseprefix=''
     23       shift
     24       ;;
     25     -o|--octal)
     26       obase=8
     27       baseprefix='0o'
     28       shift
     29       ;;
     30     -b|--binary)
     31       obase=2
     32       baseprefix='0b'
     33       shift
     34       ;;
     35     -h|--help)
     36       usage
     37       exit 0
     38       ;;
     39     --) # end arg parsing
     40       shift
     41       break
     42       ;;
     43     -*) # unsupported flags
     44       echo "Unsupported flag $1" >&2
     45       exit 1
     46       ;;
     47     *) # preserve positional arguments
     48       PARAMS="$PARAMS $1"
     49       shift
     50       ;;
     51   esac
     52 done
     53 eval set -- "$PARAMS"
     54 
     55 case "$1" in
     56   0x*) ibase=16; val="$(printf "%s" "${1#0x}" | tr '[:lower:]' '[:upper:]')";;
     57   0d*) ibase=10; val="${1#0d}";;
     58   0o*) ibase=8; val="${1#0o}";;
     59   0b*) ibase=2; val="${1#0b}";;
     60   *) ibase=10; val="$1";;
     61 esac
     62 
     63 if [ -n "$obase" ]; then
     64   printf "%s%s" "$baseprefix" "$(printf "obase=%s; ibase=%s; %s\n" "$obase" "$ibase" "$val" | bc -w | tr -d '\n')"
     65 else
     66   printf "Dec: %s\n" "$(printf "obase=10; ibase=%s; %s\n" "$ibase" "$val" | bc -w)" \
     67     && printf "Hex: %s\n" "$(printf "obase=16; ibase=%s; %s\n" "$ibase" "$val" | bc -w)" \
     68     && printf "Oct: %s\n" "$(printf "obase=8; ibase=%s; %s\n" "$ibase" "$val" | bc -w)" \
     69     && printf "Bin: %s\n" "$(printf "obase=2; ibase=%s; %s\n" "$ibase" "$val" | bc -w)"
     70 fi
     71