1

I need to convert a string to an unsigned 32 bit integer (Cardinal).

In System.SysUtils unit there are many useful functions like:

  • StrToInt
  • StrToInt64
  • StrToUInt64

But I can't find any StrToCardinal, StrToUInt or StrToUInt32 function.

10
  • 6
    StrToUInt? Commented Jan 22, 2021 at 9:20
  • Why do you need one? Why isn't := StrToInt() enough for you? Have you encountered an actual problem? There also exists no StrToWord() and StrToByte()... Commented Jan 22, 2021 at 9:21
  • @AndreasRejbrand: I can't find it in my System.SysUtils (DelphiXE7), how is it implemented? Commented Jan 22, 2021 at 9:23
  • @AmigoJack: I know, but I have to work with Cardinal values (i.e: PIDs) Commented Jan 22, 2021 at 9:24
  • 2
    @Fabrizio: I suspected that. It merely converts the string to a 64-bit integer, checks if it is within a cardinal's range, and if so casts and if not raises an exception. It's a trivial three-liner. Commented Jan 22, 2021 at 9:25

1 Answer 1

3

To follow Andreas Rejbrand idea posted as comment, I would suggest this:

function StrToCardinal(const S : String) : Cardinal;
var
    I64 : UInt64;
begin
    I64 := StrToUInt64(S);
    if (I64 shr 32) <> 0 then
        raise EConvertError.Create('StrToCardinal invalid value');
    Result := Cardinal(I64);
end;
Sign up to request clarification or add additional context in comments.

4 Comments

@AmigoJack: The OP said in the Q that StrToUInt64 exists. It's the third bullet in the list.
@DavidHeffernan: I am afraid I don't quite see what you mean by giving that link. The OP already said that the function exists in XE7 and a link to the Sydney docs doesn't say much about the situation in XE7. Perhaps you meant to (1) give the link docwiki.embarcadero.com/Libraries/XE7/en/… and (2) address the comment to AmigoJack?
@AmigoJack I tested my code with D10.4.1 and the OP said StrToUInt64 already existed at XE7 time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.