Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Double to an Integer for GetHashCode in Delphi

Delphi 2009 added the GetHashCode function to TObject. GetHashCode returns an Integer which is used for hashing in TDictionary.

If you want an object to work well in TDictionary, you need to override GetHashCode appropriately such that, in general, different objects return different integer hash codes.

But what do you do for objects containing double fields? How do you turn those double values into a integers for GetHashCode?

The way it's usually done in Java, say, is to use a method like Double.doubleToLongBits or Float.floatToIntBits. The latter has documentation that describes it as follows: "Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout." This involves some bitwise operations with different masks for the different bits of a floating point value.

Is there a function that does this in Delphi?

like image 536
MB. Avatar asked Dec 23 '22 09:12

MB.


1 Answers

I'd suggest the following improvement over the Gamecat code:

type
  TVarRec = record
    case Integer of
      0: ( FInt1, FInt2 : Integer; )
      1: ( FDouble : Double; )
  end;

function Convert(const ADouble: Double): Integer;
var
  arec : TVarRec;
begin
  arec.FDouble := ADouble;
  Result := arec.FInt1 xor arec.FInt2;
end;

This takes into account all the bits of the Double value.

(comments do not work well with code)

like image 184
Greg Avatar answered Dec 28 '22 07:12

Greg