Val不能与UInt64一起使用?

Dav*_*ric 4 delphi delphi-xe2

只是好奇为什么以下代码无法在字符串表示中转换uint64值?

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.
Run Code Online (Sandbox Code Playgroud)

德尔福XE2

我在这里错过了什么吗?

Arn*_*hez 5

你说得对:Val()不兼容UInt64 / QWord.

有两个重载函数:

  • 一个返回浮点值;
  • 一个返回Int64(即签名值).

您可以使用此代码:

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;
Run Code Online (Sandbox Code Playgroud)

它可以在Unicode而不是Unicode版本的Delphi中使用.

出错时,返回0.

  • @DavidHeffernan我有几个这样的函数变体,一个使用`var error:integer`附加参数.返回0确实有意义,具体取决于上下文(例如在我们的*mORMot*框架中).这只是为了展示一种实现模式.@TLama这段代码将从Delphi 2到XE2,包括64位版本的XE2,以及FPC,我想. (2认同)