=> 🏠 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.

Proxy Information
Original URL
gemini://laniakea.rodoste.de/journal/2023-11-04-base-conversion-in-bash.gmi
Status Code
Success (20)
Meta
text/gemini; lang=en; charset=utf-8
Capsule Response Time
257.59275 milliseconds
Gemini-to-HTML Time
0.434397 milliseconds

This content has been proxied by September (3851b).