Prevent bc from auto truncating leading zeros when converting from hex to binary
The output from bc
is correct; it simply isn't what you had in mind (but it is what the designers of bc
had in mind). If you converted hex 4F
to decimal, you would not expect to get 079 out of it, would you? Why should you get leading zeroes if the output base is binary? Short answer: you shouldn't, so bc
doesn't emit them.
If you must make the binary output a multiple of 8 bits, you can add an appropriate number of leading zeroes using some other tool, such as awk
:
awk '{ len = (8 - length % 8) % 8; printf "%.*s%s\n", len, "00000000", $0}'
You can pipe to awk
like this:
echo "ibase=16; obase=2; $line" | BC_LINE_LENGTH=9999 bc | awk '{ printf "%08d\n", $0 }'