Convert INT -> Base X -> INT  

Send By: Chris Baldwin
Web : N.A.
Email: N.A.
Date: 30/04/02

Tip accessed 480 times

 


With those functions we can convert between base 10 and other bases (Hexadecima, Octal, Binary, etc)


  • Put a TMemo (Memo1) and a TButton (Button1) in your form
  • Put this code into OnClick event of Button1:


     procedure TForm1.Button1Click(Sender: TObject);
    
       const B36 : PChar = ('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ');
    
       function IntToBase(iValue: integer; Base: byte; Digits: byte): string;
       begin
         result := '';
         repeat
           result := B36[iValue MOD BASE]+result;
           iValue := iValue DIV Base;
         until (iValue DIV Base = 0);
         result := B36[iValue MOD BASE]+result;
         while length(Result) < Digits do Result := '0' + Result;
       end;
    
       function BaseToint(iValue: String; Base: byte): integer;
       var
         i: byte;
       begin
         result := 0;
         for i := 1 to length(iValue) do begin
           if (pos(iValue[i], B36)-1) < Base then
             result := result * Base + (pos(iValue[i], B36)-1)
           else begin
             result := 0;
             break;
           end;
         end;
       end;
    
    
     var
       n   : integer;
     begin
       {Un ejemplo: mostramos decimal, Hexadecimal y Octal}
       {An example, shows Decimal, Hexadecimal and Octal}
       for n:= 0 to 500 do begin
         Memo1.Lines.Add( 'Dec:'+IntToStr(n)+^I+
                          'Hex:'+IntToBase(n,16,3)+^I+
                          'Oct:'+IntToBase(n,8,3) );
    
       end;
     end;