Linux – convert text file of bits to binary file

bashbinary fileslinuxxxd

I have a file instructions.txt with the contents:

00000000000000000000000000010011
00000010110100010010000010000011
00000000011100110000001010110011
00000000011100110000010000110011
00000000011100110110010010110011
00000000000000000000000000010011

How can I create a binary file instructions.bin of the same data as instructions.txt. In other words the .bin file should be the same 192 bits that are in the .txt file, with 32 bits per line. I am using bash on Ubuntu Linux. I was trying to use xxd -b instructions.txt but the output is way longer than 192 bits.

Best Answer

oneliner to convert 32-bit strings of ones and zeros into corresponding binary:

$ perl -ne 'print pack("B32", $_)' < instructions.txt > instructions.bin

what it does:

  • perl -ne will iterate through each line of input file provided on STDIN (instructions.txt)
  • pack("B32", $_) will take a string list of 32 bits ($_ which we just read from STDIN), and convert it to binary value (you could alternatively use "b32" if you wanted ascending bit order inside each byte instead of descending bit order; see perldoc -f pack for more details)
  • print would then output that converted value to STDOUT, which we then redirect to our binary file instructions.bin

verify:

$ hexdump -Cv instructions.bin
00000000  00 00 00 13 02 d1 20 83  00 73 02 b3 00 73 04 33  |...... ..s...s.3|
00000010  00 73 64 b3 00 00 00 13                           |.sd.....|
00000018

$ xxd -b -c4 instructions.bin
00000000: 00000000 00000000 00000000 00010011  ....
00000004: 00000010 11010001 00100000 10000011  .. .
00000008: 00000000 01110011 00000010 10110011  .s..
0000000c: 00000000 01110011 00000100 00110011  .s.3
00000010: 00000000 01110011 01100100 10110011  .sd.
00000014: 00000000 00000000 00000000 00010011  ....