如何为不支持UInt64的编译器版本编写无符号64位整数的比较函数



如何使用Delphi 6做到这一点?UInt64在Delphi 6中是未知的。它在后来的版本中被引入。

var
  i, j: Int64;
  if UInt64(i) < UInt64(j) then ...

I am thinking of an asm procedure. 
function UInt64CompareLT(i, j: Int64): Boolean;
asm
 ???
end;
function UInt64CompareGT(i, j: Int64): Boolean;
asm
 ???
end;

SysUtils中的Int64Rec类型是为挑选64位整数的部分而设计的。

如果你碰巧使用的是一个早于这种类型的Delphi,请自己定义它:

type
  Int64Rec = packed record
    case Integer of
      0: (Lo, Hi: Cardinal); 
      1: (Cardinals: array [0..1] of Cardinal); 
      2: (Words: array [0..3] of Word);
      3: (Bytes: array [0..7] of Byte);
  end;

更重要的是,您只需要一个返回-1表示小于,1表示大于,0表示等于的函数。类似这样的东西:

function CompareUInt64(const i, j: Int64): Integer;
begin
  if Int64Rec(i).Hi < Int64Rec(j).Hi then
    Result := -1
  else if Int64Rec(i).Hi > Int64Rec(j).Hi then
    Result := 1
  else if Int64Rec(i).Lo < Int64Rec(j).Lo then
    Result := -1
  else if Int64Rec(i).Lo > Int64Rec(j).Lo then
    Result := 1
  else
    Result := 0;
end;

这个想法是,你首先比较高阶部分,只有当它相等时,你才能继续比较低阶部分。

这可以通过Cardinal的比较函数而变得更简单。

function CompareCardinal(const i, j: Cardinal): Integer;
begin
  if i < j then
    Result := -1
  else if i > j then
    Result := 1
  else
    Result := 0;
end;
function CompareUInt64(const i, j: Int64): Integer;
begin
  Result := CompareCardinal(Int64Rec(i).Hi, Int64Rec(j).Hi);
  if Result = 0 then
    Result := CompareCardinal(Int64Rec(i).Lo, Int64Rec(j).Lo);
end;

最后,如果您需要问题的布尔函数,它们可以在这个更通用的函数之上实现。

没有必要使用汇编程序(但是,当然,你可以这样做):你可以比较Int64的高低部分:

  function UInt64CompareLT(i, j: Int64): Boolean;
  begin
    if (LongWord(i shr 32) < LongWord(j shr 32)) then
      Result := true
    else if (LongWord(i shr 32) > LongWord(j shr 32)) then
      Result := false
    else if (LongWord(i and $FFFFFFFF) < LongWord(j and $FFFFFFFF)) then
      Result := true
    else
      Result := false;
  end;
  function UInt64CompareGT(i, j: Int64): Boolean;
  begin
    if (LongWord(i shr 32) > LongWord(j shr 32)) then
      Result := true
    else if (LongWord(i shr 32) < LongWord(j shr 32)) then
      Result := false
    else if (LongWord(i and $FFFFFFFF) > LongWord(j and $FFFFFFFF)) then
      Result := true
    else
      Result := false;
  end;

使用汇编程序是可能的,但会将代码绑定到特定的机器体系结构
你可以在纯Pascal中实现这一点,如下所示:

type
  //Delcare a variant record to have 2 ways to access the same data in memory.
  T64Bit = record
  case Integer of
    0: (I64: Int64;);
    1: (Small: Cardinal; Big: Cardinal);
  end;
var
  I, J: T64Bit;
begin
  //You can set the value via normal Int64 assignment as follows:
  I.I64 := 1;
  J.I64 := 2;
  //Then you can compare the "big" and "small" parts on the number using
  //unsigned 32-bit comparisons as follows.
  if (I.Big < J.Big) or ((I.Big = J.Big) and (I.Small< J.Small)) then
  //The logic is as follows... 
  //  If the big part is less than, the the small part doesn't matter
  //  If the big parts are equal, then the comparison of the small parts determines the result.

最新更新