Search code examples
bashhexhexdumpbc

How do you Pipe hex data directly to bc and converting it to binary - cleanly?


Hex (character) to binary conversion is useful, especially when you want to look at a few bits mushed inside some hex string.

It is for this reason that I would like to pipe some hex data to bc (the Unix program known as 'basic calculator') and convert it to binary characters (1s and 0s).

Generally I would like to cat a file of hex data (lines hex data in a file) and pipe it to bc and have bc convert it to binary. Alternatively I could convert a binary file to hex with xxd and pipe that to bc.

There are ways to do this, but given that bc needs a few directives, all the methods seem a bit convoluted. How can this be done simply, without a bash script with some for loop?


Solution

  • I think this does what you want.

    { echo "obase=2; ibase=16"; xxd -c 32 -u -p file.bin; } | bc
    

    It just feeds both the settings and the streamed file contents to bc with a brace list. The -u flag to xxd makes it output upper case hex letters.