0

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?

Xofo
  • 1,256
  • 4
  • 18
  • 33
  • 1
    What's the question here exactly? – Etan Reisner Jul 22 '15 at 02:43
  • I have rewritten the question. I am using bc to convert Hex to Binary. I am seeking a better way to do it. – Xofo Jul 22 '15 at 02:48
  • Thanks - Looks okay, but returned > character , I think there is a syntax error in your solution. Good start though. – Xofo Jul 22 '15 at 03:04
  • The result yielded many: 0 0 (standard_in) 21788: parse error (standard_in) 21789: parse error (standard_in) 21790: parse error (standard_in) 21791: parse error – Xofo Jul 22 '15 at 03:09
  • You are right ... I missed the "-u" ... Thanks! Good solution. – Xofo Jul 22 '15 at 03:18

2 Answers2

1

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.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
0

Since StackOverflow, encourages answering your own question, this is my solution:

xxd -c 32 -p file.bin | awk '{print toupper($0)}' | tr '\n' ' ' |  { read line; for i in $line; do echo "obase=2; ibase=16; $i" | bc ; done }

I do not like my solution because it seems convoluted. I would like to devise a way to pipe the output of xxd to bc, without the for loop, and without using tr (which I could have used to uppercase as well). Anyway, it works but I think it can be done better.

Xofo
  • 1,256
  • 4
  • 18
  • 33
  • 1
    This would seem to be an integral part of the question since the question, on its own, is still rather lacking an actual full question. – Etan Reisner Jul 22 '15 at 02:53
  • Ideally I would like to craft the most optimal question. This answer can live it its state, I am sure a better answer will appear. – Xofo Jul 22 '15 at 03:06