Pascal: Reading A Message From a File of Bits

program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils;
//convert a file of comma separated binary digits
//into a message of ASCII characters

function power(m:integer):integer;
//function returns 2 ^ index
var
i,r:integer;
begin
r:=1;
for i:= 1 to m do
r:= r * 2; //multiply repeatedly by 2 to get result
power:=r;
end;

function binary_denary(asciistring:string; ascnum:integer):integer;
//convert string of 8 bits to decimal
var
i, digit : integer;
begin
ascnum:=0;
if (length (asciistring)=8) then
for i:=1 to 8 do
begin
digit:= strtoint(asciistring[i]);
if digit = 1 then //check for 1 or 0
ascnum:=ascnum + power(8-i); //2 to power 7,6,5,4,3,2,1,0
end;
binary_denary:=ascnum;
end;

procedure readfile;
var s:integer;
binarydigit:char;
asciinumber:integer;
asciistring,mymessage:string;
binaryfile:text;
begin
assign(binaryfile, 'binarymessage.txt');
reset(binaryfile);
asciinumber:=0;
s:=1;
while not eof(binaryfile)do
begin
asciistring:='';
repeat
read(binaryfile, binarydigit);
if not (binarydigit=',') then asciistring:=asciistring+binarydigit;
inc(s);
until (s mod 16=0); //one ASCII character per 16 characters from file
mymessage:=mymessage + chr(binary_denary(asciistring,asciinumber)); //add character to message string
end;
writeln(mymessage);
closefile(binaryfile);
end;

begin
writeln('Convert a string of binary digits into text');
readfile;
readln;
end.

Procedure readfile opens the file of comma separated bits and reads them one at a time. Within the while not eof loop there is a second loop that examines the character read: if it is not a comma then it is added to the current 8 bit string (asciistring); this continues until a group of 16 characters has been read, at which point there should be an 8 bit string that can be converted to decimal. After conversion to decimal the equivalent character can be found and this is added to the message string.

Extension: now you can read a file of binary digits you should be able to isolate individual bits such as parity bits and you could also group bits into larger words ready for encryption e.g. 16 bit words encrypted with a 16 bit key (using XOR). Or 32 bit words, or 64 bit words...

And then there is the opposite process of converting a text message into a CSV file of bits.