Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

base conversion calculation 1

Status
Not open for further replies.

stumanoo

Technical User
May 29, 2003
2
GB
probably a long shot but does anyone have the delphi pascall code for converting a base 4 (Quad) number to a base 16(hex) number.


or even just how to calculate this

thanx

 
If you can work out a way of converting quad to binary then you could use the BinToHex routine but it's a bit of a roundabout method.

Clive [infinity]
Ex nihilo, nihil fit (Out of nothing, nothing comes)
 
Here's a crude and quick example I knocked up... you'd need to test it properly and modify if necessary. Someone will no doubt show a quicker and more accurate way to do it (Zathras ;-))! The quad value is assumed to be in Edit3.Text and the output is displayed in label1. One thing it doesn't deal with is floating-point quad numbers - it assumes the quad number to be an integer.
Code:
var
  counter: Integer;
  individualDigit: Integer;
  exponentCounter: Integer;
  total: Double;
  quadValue: String;
begin
  total := 0;
  exponentCounter := 0;
  quadValue := Trim(Edit3.Text);
  for counter := Length(quadValue) downto 1 do
  begin
    individualDigit := StrToInt(quadValue[counter]);
    total := total + (individualDigit * Power(4, exponentCounter));
    Inc(exponentCounter);
  end;
  label1.Caption := Format('%x',[Round(total)]);
end;

Clive [infinity]
Ex nihilo, nihil fit (Out of nothing, nothing comes)
 
Ok, Clive. Only because you asked for it: This still doesn't check for a valid quad input expression. I leave it up to stumanoo to put that in if it is necessary for his application:
[red]
Code:
{ Convert a base-4 string expression to a base 10 integer }
[/color][blue]
Code:
function QuadStringToInt( AQuadNumber: string ): integer;
var
  i,n,m:integer;
begin
  Result := 0;
  m := 1;
  n := Length( AQuadNumber );
  for i := n downto 1 do
    begin
      Result := Result + StrToInt( AQuadNumber[i] ) * m;
      m := m * 4
    end;
end;
[red]
Code:
{Test QuadStringToInt() function.}
[/color]
Code:
procedure TForm1.Button1Click(Sender: TObject);
var
  n:integer;
begin
  n := QuadStringToInt(Edit1.Text);
  Edit2.Text := Format( 'Hex = %x  Decimal = %d' ,[n,n] );
end;
[/color]

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top