Val not working with UInt64?

just wondering why the following code cannot convert a uint64 value to a string representation?

var num: UInt64; s: string; err: Integer; begin s := '18446744073709551615'; // High(UInt64) Val(s, num, err); if err <> 0 then raise Exception.Create('Failed to convert UInt64 at ' + IntToStr(err)); // returns 20 end. 

Delphi XE2

Did I miss something?

+3
delphi delphi-xe2
source share
4 answers

According to the documentation ,

S is a string expression; it must be a sequence of characters that form a signed real number.

I agree that the documentation is a bit vague; Indeed, what exactly does form mean, and exactly what is meant by the sign of a real number (especially if num is an integer type)?

However, I think the backlight part is signed. In this case, you need an integer, so S must be a sequence of characters that form a signed integer. But then your maximum is High(Int64) = 9223372036854775807

+2
source share

You are right: Val() not compatible with UInt64 / QWord .

There are two overloaded functions:

  • One returns a floating point value;
  • Int64 returned (i.e. the signed value).

You can use this code instead:

 function StrToUInt64(const S: String): UInt64; var c: cardinal; P: PChar; begin P := Pointer(S); if P=nil then begin result := 0; exit; end; if ord(P^) in [1..32] then repeat inc(P) until not(ord(P^) in [1..32]); c := ord(P^)-48; if c>9 then result := 0 else begin result := c; inc(P); repeat c := ord(P^)-48; if c>9 then break else result := result*10+c; inc(P); until false; end; end; 

It will work in both Unicode and Unicode versions of Delphi.

On error, 0 is returned.

+4
source share
 function TryStrToInt64(const S: string; out Value: Int64): Boolean; var E: Integer; begin Val(S, Value, E); Result := E = 0; end; 
0
source share

There is really not enough documentation for this, but I use StrToUInt64 and UIntToStr from System.SysUtils , and they convert between strings and unsigned 64-bit integers.

I'm not sure when they were added to Delphi, but they are definitely in the last few releases.

0
source share

All Articles