Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex to Binary conversion in bash

Tags:

bash

hex

binary

bc

I'm trying to convert a series of bytes from hex to bin using bash. but I keep getting (seemingly random) "(standard_in) 1: syntax error" replies from the following code:

for j in c4 97 91 8c 85 87 c4 90 8c 8d 9a 83 81
do
        BIN=$(echo "obase=2; ibase=16; $j" | bc )
        echo $BIN
done

I did a similar thing with dec to bin, which works perfectly fine:

for i in {0..120}
do
        KEYBIN=$(echo "obase=2; ibase=10; $i" | bc)
        echo $KEYBIN
done

Does anyone have an idea why it works with decimal, but not with hex? In my opinion the syntax is pretty much the same (unless I'm missing something really hard.)

like image 613
fragman Avatar asked Jun 20 '12 13:06

fragman


1 Answers

I came up with this:

printf converts to hex, xxd -r -p takes the ascii hex stream and makes it actual binary

dumping with hexdump to prove it worked...

printf "%016x" 53687091200 | xxd -r -p | hexdump -C
like image 53
stu Avatar answered Oct 02 '22 04:10

stu