peterhowells

Base Conversion (Dec/Hex/Bin)

Mar 17th, 2022
1,625
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.52 KB | None | 0 0
  1. // Code to display the steps when converting from decimal to
  2.    // either binary or hexadecimal (class assignment)
  3. // Components used: frmMain, btnCalc, radToBin, radToHex, redDisplay
  4. procedure TfrmMain.btnCalcClick(Sender: TObject);
  5.   var iNum, d, q, r: integer;
  6.       s, sBin: string;
  7.  
  8. begin
  9.   redDisplay.Clear;
  10.   if ((radToBin.Checked = False) AND (radToHex.Checked = False)) then
  11.   begin
  12.     ShowMessage('You need to select which conversion to perform.');
  13.     Exit;
  14.   end;
  15.  
  16.   iNum := StrToInt(InputBox('Input', 'Enter a number:' , ''));
  17.   d := iNum;
  18.  
  19.   if (radToHex.Checked = True) then
  20.   begin
  21.     while (d > 0) do
  22.     begin
  23.       q := d Div 16;
  24.       r := d Mod 16;
  25.  
  26.       s := IntToStr(d) + ' / 16 = ' + IntToStr(q) + ' rem ' + IntToStr(r);
  27.  
  28.       redDisplay.Lines.Add(s);
  29.       d := q;
  30.     end;
  31.  
  32.     if (d = 0) then
  33.     begin
  34.       redDisplay.Lines.Add('');
  35.       s :=  'Therefore, ' + IntToStr(iNum) + ' = 0x' + IntToHex(iNum, 1);
  36.       redDisplay.Lines.Add(s);
  37.     end;
  38.   end
  39.  
  40.   else if (radToBin.checked = True) then
  41.   begin
  42.     sBin := '';
  43.  
  44.     while (d > 0) do
  45.     begin
  46.       q := d Div 2;
  47.       r := d Mod 2;
  48.  
  49.       insert(IntToStr(r), sBin, 1);  // create binary string
  50.  
  51.       s := IntToStr(d) + ' / 2 = ' + IntToStr(q) + ' rem ' + IntToStr(r);
  52.  
  53.       redDisplay.Lines.Add(s);
  54.       d := q;
  55.     end;
  56.  
  57.     if (d = 0) then
  58.     begin
  59.       redDisplay.Lines.Add('');
  60.       s :=  'Therefore, ' + IntToStr(iNum) + ' = 0b' + sBin;
  61.       redDisplay.Lines.Add(s);
  62.     end;
  63.   end;
  64. end;
Advertisement