bashbczero-padding

How to make `bc` output a desired number of base-2 binary digits


This outputs 101110

echo "obase=2; 46" | bc

How can I make it output 8 digits, like this? : 00101110

I learned the above usage of bc here: Bash shell Decimal to Binary base 2 conversion

See also my answer to that question here.


Solution

  • The simple solution is to use the output of bc within a command substitution providing input to printf using the "%08d" conversion specifier, e.g.

    $ printf "%08d\n" $(echo "obase=2; 46" | bc)
    00101110