Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent bc from auto truncating leading zeros when converting from hex to binary

Tags:

bash

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?

like image 423
gp_xps Avatar asked Sep 28 '12 04:09

gp_xps


2 Answers

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}'
like image 199
Jonathan Leffler Avatar answered Sep 28 '22 00:09

Jonathan Leffler


You can pipe to awk like this:

echo "ibase=16; obase=2; $line" | BC_LINE_LENGTH=9999 bc | awk '{ printf "%08d\n", $0 }' 
like image 22
Steve Avatar answered Sep 28 '22 00:09

Steve