7

I have a hexadecimal string value. I want to convert it to an integer.

function HexStrToInt(const str: string): Integer;
begin
  Result := ??;
end;

such that HexStrToInt('22'), for example, returns 34.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Levent Tulun
  • 701
  • 3
  • 9
  • 22
  • 2
    possible duplicate of [Convert hex str to decimal value in delphi](http://stackoverflow.com/questions/13841972/convert-hex-str-to-decimal-value-in-delphi) – Nadeem Iqbal Mar 26 '15 at 14:55
  • 4
    FWIW, I edited your question a little. You did say that you wanted a decimal integer returned. That's an oxymoron. An integer contains a value. Decimal or hexadecimal or binary or octal etc. refer to representations of the value. So, $22 and 34 are in fact the same value, but different representations of that value. – David Heffernan Mar 26 '15 at 14:58
  • thank you, you are the best delphi master :) – Levent Tulun Mar 26 '15 at 15:05
  • @NadeemIqbal: No, it isn't. They're different questions. – Ken White Mar 26 '15 at 15:11
  • 1
    @LeventTulun Quickest perhaps, best, not so much!! ;-) – David Heffernan Mar 26 '15 at 15:15
  • 2
    @DavidHeffernan 10,000+ answered questions shows at least how invaluable you are to stackoverflow, you have my respect :) – Craig Mar 26 '15 at 22:31

1 Answers1

26

Perhaps the simplest is to do this:

function HexStrToInt(const str: string): Integer;
begin
  Result := StrToInt('$' + str);
end;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 6
    Additionally, as may be useful, `function TryHexStrToInt(const str : string; out value:integer) : boolean;` with `result := TryStrToInt('$' + str, value)`. Useful for catching errors if the input is not guaranteed to be well formatted. http://docwiki.embarcadero.com/Libraries/en/System.SysUtils.TryStrToInt – J... Mar 26 '15 at 15:36
  • I know this answer is old, but can you tell me how you were able to find out how this is implemented? When i look into the implementation (10.4) i come accross the line Val(S, Result, E); in System.SysUtils which links val to the System unit and there i am stuck to find the conversion. – Eggi Jul 16 '21 at 07:15
  • 2
    @eggi I didn't learn this from the code, and the implementation is somewhat buried in the system unit as an intrinsic function. However, you don't need to look at the implementation since this behaviour is documented: http://docwiki.embarcadero.com/Libraries/en/System.SysUtils.StrToInt – David Heffernan Jul 16 '21 at 08:03
  • 1
    @Eggi but if you do want to look at the implementation, say out of curiosity, then just use the debugger to take you there. Enabled debug DCUs and step in to `StrToInt`. That will take you in to `_ValLong` in `System`. – David Heffernan Jul 16 '21 at 08:05