How to convert text to binary code in Pascal

1 Answer

0 votes
program TextToBinary;

uses
  SysUtils;

function IntToBin(Value: Integer): string;
var
  BinStr: string;
begin
  BinStr := '';
  while Value > 0 do
  begin
    if (Value mod 2) = 1 then
      BinStr := '1' + BinStr
    else
      BinStr := '0' + BinStr;
    Value := Value div 2;
  end;
  IntToBin := BinStr;
end;

function TextToBin(txt: string): string;
var
  Bin: string;
  i: Integer;
  CharCode: Integer;
  Binary: string;
begin
  Bin := '';
  for i := 1 to Length(txt) do
  begin
    CharCode := Ord(txt[i]); // Get ASCII value of the character
    Binary := IntToBin(CharCode); // Convert ASCII value to binary
    
    // Ensure binary is padded to 8 bits
    while Length(Binary) < 8 do
      Binary := '0' + Binary;
      
    Bin := Bin + Binary + ' ';
  end;
  TextToBin := Trim(Bin); // Remove trailing space
end;

begin
  Writeln(TextToBin('Pascal'));
end.



(*
run:

01010000 01100001 01110011 01100011 01100001 01101100

*)

 



answered Apr 13, 2025 by avibootz
...