Bash – Convert a value into a “Binary Number” in a shell script

bashshell

I know of bc:

$> var="304"
$> echo "obase=2; $var" | bc
100110000

Could it be done in shell (no external call)?

This question:
Binary to hexadecimal and decimal in a shell script
Asks how to convert FROM binary, not TO a binary number.

The answers there deal either with binary byte (as opposed to binary number, i.e.: a base-2 number) using xxd, or some other external tool. So, no, this question is not a duplicate of that.

Best Answer

In bash:

toBinary(){
    local n bits sign=''
    (($1<0)) && sign=-
    for (( n=$sign$1 ; n>0 ; n >>= 1 )); do bits=$((n&1))$bits; done
    printf "%s\n" "$sign${bits-0}"
}

Use:

$> toBinary 304
100110000

Or more POSIX_ly:

toBinaryPOSIX(){
    n=$(($1))
    bits=""
    sign=""
    if [ "$n" -lt 0 ]; then
        sign=- n=$((-n))
    fi
    while [ "$n" -gt 0 ]; do
        bits="$(( n&1 ))$bits";
        : $(( n >>= 1 ))
    done
    printf "%s\n" "$sign${bits:-0}"
}

Use:

$> toBinaryPOSIX 304
100110000

If Value is hex:

$> toBinaryPOSIX 0x63
1100011
Related Question