0

Yes, I have seen Bash shell Decimal to Binary base 2 conversion , but I cannot tell how to do the following easily:

Say, I want to convert the decimal number 47803625 to a 32-bit binary string, that is 0b00000010110110010110110011101001. Closest I could get to is this:

$ printf "0b%32s\n" $(echo "obase=2; 47803625" | bc)
0b      10110110010110110011101001

... however, this pads the string on the left with spaces, not zeroes.

(sidenote: if I try the above with the %d format specifier, it fails:

$ printf "0b%32d\n" $(echo "obase=2; 47803625" | bc)
bash: printf: warning: 10110110010110110011101001: Numerical result out of range
0b             9223372036854775807

)

What would be an easy way to do this kind of a conversion from the command line? I'd be fine with a Python or other solution as well - as long as it is a one-liner I can type in a terminal ...

sdbbs
  • 4,270
  • 5
  • 32
  • 87

1 Answers1

1

Eh, found it - simply prepend a 0 to the %32s format specifiers, then zeroes are used to left pad, even for a string %s format specifier:

$ printf "0b%032s\n" $(echo "obase=2; 47803625" | bc)
0b00000010110110010110110011101001
sdbbs
  • 4,270
  • 5
  • 32
  • 87