Val不能与UInt64一起使用?

时间:2012-08-04 12:52:26

标签: 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.

Delphi XE2

我在这里错过了什么吗?

4 个答案:

答案 0 :(得分: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;

它适用于Unicode而不是Unicode版本的Delphi。

出错时,返回0.

答案 1 :(得分:3)

根据the documentation

  

S是字符串类型表达式;它必须是一个形成有符号实数的字符序列。

我同意文件有点模糊;实际上,形式究竟是什么意思,而一个有符号的实数究竟是什么意思(特别是如果num是整数类型的话)?

不过,我认为要突出显示的部分是已签名。在这种情况下,您需要一个整数,因此S必须是字符序列,形成有符号整数。但那么你的最大值是High(Int64) = 9223372036854775807

答案 2 :(得分:0)

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

答案 3 :(得分:0)

关于此的文档确实缺乏,但我使用StrToUInt64中的UIntToStrSystem.SysUtils,它们在字符串和无符号64位整数之间进行转换。

我不确定这些是什么时候添加到Delphi中的,但它们肯定是在最后几个版本中。

相关问题