I've got a load of binary data stored as ASCII text in a file like this:

0b 0000 0001
0b 0000 0000
0b 1111 0001 

How would I convert this to a raw binary bitstream, and save it to disk?

Can this be done with standard unix tools?

  • So binary representation (not hexadecimal), with one byte per line, a space between the nibbles and a prefix of "0x " ? – Ángel Dec 6 '20 at 21:51
  • "0b" not "0x" that was a typo. But yeah, binary representation – Persistence Dec 6 '20 at 21:55
  • It is possible to generate this output with xxd -c 1 -b | sed 's/^[0-9a-f]*:/0b/' | cut -f 1-2 -d\ but xxd doesn't support -b with -r :/ – Ángel Dec 6 '20 at 22:07

Have not fully fleshed this out but try the following:

$ cat demo.sh

while read bb nibble1 nibble2
    byte=$(printf "%s%s" ${nibble1} ${nibble2} )
    hexstr=$(printf '\\\\x%02x' $((2#${byte})) )
    eval printf "$hexstr"
done < infile > outfile

Using your sample input:

$ ./demo.sh

$ xxd outfile
00000000: 0100 f1                                  ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.