🏠 home

base conversion script for BASH

2023-11-04

I got tired of starting a calculator or wasting energy by doing an internet query to convert numerical bases so I wrote a script.

Update 2023-11-08: Emilis reached out and suggested to swap the order of the input parameters. This would make aliassing the script much easier. That's a great idea! Thanks Emilis! The script below is updated as per their suggestion.

Shell scripts are powerful. Each shell command — and there are many of them — does one thing and does it well. It is the combination of these building blocks that multiply their potential.

Anyway.

At times I need to do a lot of conversions between decimal, hexadecimal and binary numbers. Over time I've gotten somewhat okay of doing _some_ of them in my head or simply remembering them. But regardless I had to use a calculator or use a conversion website, which was tiring.

So eventually I got around to writing a short shell script.

    #!/usr/bin/env bash

    if [ $# -ne 2 ]; then
      basename=$(basename $0)
      echo "Converts a decimal number into another base"
      echo "Usage: $basename target_base decimal_number"
      echo
      echo "Examples:"
      echo "  $basename 2 30     converts decimal 30 to binary 11110"
      echo "  $basename 16 73    converts decimal 73 to hexadecimal 4B"
      exit 1
    fi

    decimalNum=$2
    obase=$1
    prefix=""

    # convert bases
    if   [[ $obase == "h" || $obase == "hex" ]]; then obase=16
    elif [[ $obase == "o" || $obase == "oct" ]]; then obase=8
    elif [[ $obase == "b" || $obase == "bin" ]]; then obase=2
    fi

    # helpful prefixes
    if   [ $obase -eq 16 ]; then prefix="0x"
    fi

    targetNum=$(echo "obase=$obase;$decimalNum" | bc)
    echo "$decimalNum in base $obase is $prefix$targetNum"

As is usually the case, the actual logic of the script is quite short — in this case: a single line — and the majority is taken up by input sanitation, usage hints and convenience conversion.

`bc` is actually a complete calculator, capable of so much more. But I'm scripting it by setting it to an output conversion base and then simply passing a decimal number.

aliases

Let's say you need conversion to hexadecimal more than anything else. With the updated parameter order you can make an alias like `alias to-hex='bases.sh 16'` and use it conveniently as `# to-hex 73`. Nice. Thanks again Emilis!

Links

bc on gemini

https link to the bc man page

---

see all my articles


Source