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
bcis correct; it simply isn’t what you had in mind (but it is what the designers ofbchad in mind). If you converted hex4Fto 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, sobcdoesn’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: