Home > Software engineering >  Writing bits (not hex values) to file in Linux
Writing bits (not hex values) to file in Linux

Time:08-20

I am trying to teach how a computer operates using binary information. To showcase this, I would like to take a string of bits: 011010000110010101101100011011000110111100100000011101110110111101110010011011000110010000001010 and write it to a file.

I can do it using HEX: echo -n -e \\x48\\x65\\x6c\\x6c\\x6f\\x20\\x57\\x6f\\x72\\x6c\\x64\\x0a > text.txt but haven't been able to figure out how to do it using binary numbers.

Is it possible to write raw bits to a file using a Linux terminal?

CodePudding user response:

perl to the rescue:

$ perl -e 'print pack("B*", $ARGV[0])' 011010000110010101101100011011000110111100100000011101110110111101110010011011000110010000001010 > test.txt
$ xxd test.txt
00000000: 6865 6c6c 6f20 776f 726c 640a            hello world.

CodePudding user response:

Try this :

#!/usr/bin/env bash

string=011010000110010101101100011011000110111100100000011101110110111101110010011011000110010000001010

for ((i=0; i<${#string}; i =8)); do
    printf %b $(printf '\\xx' $((2#${string:i:8})))
done
  • Related