Programs to Complete: Converting Denary to Binary

Writing programs to inter-convert denary, hexadecimal and binary representations of numbers is excellent practice to reinforce the theory. Some students find it difficult to get started, but then quickly progress once given some help. Program Denary2Binary begins to carry out the conversion in the way the theory textbooks suggest, but it is not an elegant solution and it is restricted to integers less than 256. Try the following to complete the program:

  • Add the remaining lines to output the complete binary string then test your result.
  • Make the solution neater by putting it into a loop.
  • Adapt it so that it will convert integers up to, say, 216.
program Denary2Binary;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  Int, ErrorCode : integer;
  strInt : string;
procedure DisplayBinary(Number: integer);
var
  BinaryString : string;
  Remainder128, Remainder64, Remainder32, Remainder16,
  Remainder8, Remainder4, Remainder2: integer;
begin
  BinaryString := '';
  if Number DIV 128 = 1 then  //Most significant bit
    begin
      BinaryString := BinaryString + '1';
    end
  else
    begin
      BinaryString := BinaryString + '0';
    end;
  Remainder128 := Number MOD 128;
  if Remainder128 DIV 64 = 1 then   //Second bit from left
    begin
      BinaryString := BinaryString + '1';
    end
  else
    begin
      BinaryString := BinaryString + '0';
    end;
  BinaryString := BinaryString + 'xxxxxx'; //Line to be deleted
  Remainder64 := Remainder128 MOD 64;
  writeln('Binary representation: ', BinaryString);
end;

begin
  repeat
    write('Please enter a denary integer from 0 to 255. ');
    readln(strInt);
    val(strInt, Int, ErrorCode);
    DisplayBinary(Int);
  until ErrorCode = 0;
  readln;
end.

Programming - a skill for life!

Unfinished programs for you to complete