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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With