I'm trying to convert a hex string to binary. I'm using:
echo "ibase=16; obase=2; $line" | BC_LINE_LENGTH=9999 bc
It is truncating the leading zeroes. That is, if the hex string is 4F
, it is converted to 1001111
and if it is 0F
, it is converted to 1111
. I need it to be 01001111
and 00001111
What can I do?
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 }'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With