Convert a decimal number to binary from Bash

Suppose we are working on a bash script and that for some need, not too difficult from reality, it is essential to have to convert a number or a decimal variable into a binary number.

There are of course several solutions but the one I propose does not make use of external programs but it is bash in all respects.

First we need to know the maximum value of the binary number to be obtained in Bash or in how many bits it can be included.

We consider that we are talking about a byte and therefore 8 bits and that its binary range will go from 00000000 to 11111111 (from 0 to 255) then we can write:

echo ${bin[*]}
Convert a decimal number to binary from Bash
bash - binary number array

The more is done, in fact, to have the result for example of the number 125 or 78 in binary is enough

echo ${bin[125]}
echo ${bin[78]}

If the range of the binary number changes, for example if we double or quadruple it is enough that we define the bin variable with one or two more blocks of the type {0..1}.

So summing up, the bin variable will have to contain as many blocks {0..1} based on the maximum binary number to be obtained, that is, if the maximum number is 2n -1 then it will take n groups {0..1}.

As an example if n=10 and therefore 210 -1=1023 the blocks will be 10

echo ${bin[1023]}

Leave a Reply

Your email address will not be published. Required fields are marked *

− 3 = 6