how do I make a bash script to count up in binary?

138 views Asked by At

I'm new to bash and trying to make a script of counting up in binary (0001, 0010 0011 etc.) but I have no idea how to do this, all help appreciated!

1

There are 1 answers

0
konsolebox On BEST ANSWER

Study this code:

#!/bin/bash

BINARIES=(0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111)

function convert_to_binary {
    local hex i j
    printf -v hex %x "$1"
    __=

    for (( i = 0, j = ${#hex}; i < j; ++i )); do
        __+=${BINARIES[$(( 16#${hex:i:1} ))]}
    done
}

for (( i = 0; i < 20; ++i )); do
    convert_to_binary "$i"
    printf "%8s : %16s\n" "$i" "$__"
done

for (( i = 0; i < 10; ++i )); do
    n=$RANDOM
    convert_to_binary "$n"
    printf "%8s : %16s\n" "$n" "$__"
done

Output:

       0 :             0000
       1 :             0001
       2 :             0010
       3 :             0011
       4 :             0100
       5 :             0101
       6 :             0110
       7 :             0111
       8 :             1000
       9 :             1001
      10 :             1010
      11 :             1011
      12 :             1100
      13 :             1101
      14 :             1110
      15 :             1111
      16 :         00010000
      17 :         00010001
      18 :         00010010
      19 :         00010011
   27567 : 0110101110101111
   21967 : 0101010111001111
   27236 : 0110101001100100
   28892 : 0111000011011100
   23511 : 0101101111010111
    6472 : 0001100101001000
   20723 : 0101000011110011
    8215 : 0010000000010111
    7092 : 0001101110110100
    9957 : 0010011011100101

Read the Bash Manual and printf(3).