whats new ¦  programming tips ¦  indy articles ¦  intraweb articles ¦  informations ¦  links ¦  interviews
 misc ¦  tutorials ¦  Add&Win Game

Tips (1541)

Database (90)
Files (137)
Forms (107)
Graphic (114)
IDE (21)
Indy (5)
Internet / LAN (130)
IntraWeb (0)
Math (76)
Misc (126)
Multimedia (45)
Objects/
ActiveX (51)

OpenTools API (3)
Printing (35)
Strings (83)
System (266)
VCL (242)

Top15

Tips sort by
component


Search Tip

Add new Tip

Add&Win Game

Advertising

38 Visitors Online


 
...convert numbers from one base to another?
Autor: -
[ Print tip ]  

Tip Rating (11):  
     


function BaseConvert(NumIn: string; BaseIn: Byte; BaseOut: Byte): string;
var
  
i: integer;
  currentCharacter: char;
  CharacterValue: Integer;
  PlaceValue: Integer;
  RunningTotal: Double;
  Remainder: Double;
  BaseOutDouble: Double;
  NumInCaps: string;
  s: string;
begin
  if 
(NumIn = '') or (BaseIn < 2) or (BaseIn > 36) or (BaseOut < 1) or (BaseOut > 36) then
  begin
    
Result := 'Error';
    Exit;
  end;

  NumInCaps    := UpperCase(NumIn);
  PlaceValue   := Length(NumInCaps);
  RunningTotal := 0;

  for i := 1 to Length(NumInCaps) do
  begin
    
PlaceValue       := PlaceValue - 1;
    CurrentCharacter := NumInCaps[i];
    CharacterValue   := 0;
    if (Ord(CurrentCharacter) > 64) and (Ord(CurrentCharacter) < 91) then
      
CharacterValue := Ord(CurrentCharacter) - 55;

    if CharacterValue = 0 then
      if 
(Ord(CurrentCharacter) < 48) or (Ord(CurrentCharacter) > 57) then
      begin
        
BaseConvert := 'Error';
        Exit;
      end 
      else
        
CharacterValue := Ord(CurrentCharacter);

    if (CharacterValue < 0) or (CharacterValue > BaseIn - 1) then
    begin
      
BaseConvert := 'Error';
      Exit;
    end;
    RunningTotal := RunningTotal + CharacterValue * (Power(BaseIn, PlaceValue));
  end;

  while RunningTotal > 0 do 
  begin
    
BaseOutDouble := BaseOut;
    Remainder     := RunningTotal - (int(RunningTotal / BaseOutDouble) * BaseOutDouble);
    RunningTotal  := (RunningTotal - Remainder) / BaseOut;

    if Remainder >= 10 then
      
CurrentCharacter := Chr(Trunc(Remainder + 55))
    else
    begin
      
s := IntToStr(trunc(remainder));
      CurrentCharacter := s[Length(s)];
    end;
    Result := CurrentCharacter + Result;
  end;
end;

// Example, Beispiel

procedure TForm1.Button1Click(Sender: TObject);
begin
  
BaseConvert('FFFF', 16, 10);
  // returns, ergibt '65535'.
end;

 

Rate this tip:

poor
very good


Copyright © by SwissDelphiCenter.ch
All trademarks are the sole property of their respective owners