Link to home
Start Free TrialLog in
Avatar of selas
selas

asked on

How to convert Hex to Int?

I have hex strings '00001A7000000000' ... '00001A700000012D'
how to convert each of them to unique integer
ASKER CERTIFIED SOLUTION
Avatar of Greybird
Greybird

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of illusion_chaser
illusion_chaser

Try this one:

function HexToInt2(s: string): Int64;
var
  b: Byte;
  c: Char;
begin
  Result := 0;
  s := UpperCase(s);
  for b := 1 to Length(s) do
  begin
    Result := Result * 16;
    c := s[b];
    case c of
      '0'..'9': Inc(Result, Ord(c) - Ord('0'));
      'A'..'F': Inc(Result, Ord(c) - Ord('A') + 10);
      else
        raise EConvertError.Create('No Hex-Number');
    end;
  end;
end;
What is the point of recoding a function that is in the VCL ?
Where in the VCL?
It was taken from torry's site.
And that is an alternative solution.
The function is StrToInt64, available in the SysUtils unit. You just have to prefix the string by $ pr 0x to tell this function the string you pass is hexa...
Ok for the alternative solution, but IMHO, when something is already available, you should bother recoding your own, except for a very good reason...
I think, we should let the Author decide what solution suites his needs better. BTW, your solution will work only in Delphi, while the logic that I posted (with minor changes) will work in other programming languages (and that is the good reason).
Right, he should decide.

However, we are in the Delphi section, not in the Programming one, so I suspects that he wants a Delphi solution ;)
agree with Greybird .. although there is one small caveat .. the letters must be lowercase :)
Avatar of selas

ASKER

if i use:

function hexaToInt(s : string) : Int64;
begin
  if (s <> '') and (s[1] <> '$') then
    result := strToInt64('$' + s)
  else
    result := strToInt64(s);
end;

How to convert this integer back to HexString?

e.g. 00001A7000000000 = 29068338659328
      29068338659328 = 00001A7000000000
use Format('%x', [29068338659328])
Avatar of selas

ASKER

if i use format i get: 1A7000000000
In fact you should use :
Format('%.16x', [29068338659328])
to get the padding 0s.
yeah .. it helps to read the help .. weird sentence :D