Search code examples
bashshellmathscriptingarithmetic-expressions

Convert decimal to Base-4 in bash


I have been using a pretty basic, and for the most part straight forward, method to converting base-10 numbers {1..256} to base-4 or quaternary numbers. I have been using simple division $(($NUM/4)) to get the main result in order to get the remainders $(($NUM%4)) and then printing the remainders in reverse to arrive at the result. I use the following bash script to do this:

#!/bin/bash

NUM="$1"

main() {

local EXP1=$(($NUM/4))
local REM1=$(($NUM%4))
local EXP2=$(($EXP1/4))
local REM2=$(($EXP1%4))
local EXP3=$(($EXP2/4))
local REM3=$(($EXP2%4))
local EXP4=$(($EXP3/4))
local REM4=$(($EXP3%4))

echo "
$EXP1 remainder $REM1
$EXP2 remainder $REM2
$EXP3 remainder $REM3
$EXP4 remainder $REM4

Answer: $REM4$REM3$REM2$REM1
"
}

main

This script works fine for numbers 0-255 or 1-256. But beyond this(these) ranges, results become mixed and often repeated or inaccurate. This isn't so much of a problem as I don't intend to convert numbers beyond 256 or less than 0 (negative numbers [yet]).

My question is: "Is there a more simplified method to do this, possibly using expr or bc?


Solution

  • Create a look-up table taking advantage of brace expansion

    $ echo {a..c}
    a b c    
    $ echo {a..c}{r..s}
    ar as br bs cr cs
    $ echo {0..3}{0..3}
    00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33
    

    and so, for 0-255 in decimal to base-4

    $ base4=({0..3}{0..3}{0..3}{0..3})
    $ echo "${base4[34]}"
    0202
    $ echo "${base4[255]}"
    3333