delphi double to integer

3 MB. [2009-08-17 17:15:00]

Delphi 2009 добавила функцию GetHashCode в TObject. GetHashCode возвращает целое число, которое используется для хэширования в TDictionary.

Если вы хотите, чтобы объект работал хорошо в TDictionary, вам необходимо соответствующим образом переопределить GetHashCode таким образом, чтобы в целом разные объекты возвращали разные целые хэш-коды.

Но что вы делаете для объектов, содержащих двойные поля? Как вы превращаете эти двойные значения в целые числа для GetHashCode?

Как обычно это делается в Java, скажем, использовать метод Double.doubleToLongBits или Float.floatToIntBits. Последняя имеет документацию, которая описывает ее следующим образом: «Возвращает представление указанного значения с плавающей запятой в соответствии с форматом бит» одиночный формат «с плавающей точкой IEEE 754». Это связано с некоторыми побитовыми операциями с различными масками для разных битов значения с плавающей запятой.

Есть ли функция, которая делает это в 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?

5 Answers 5

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

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

(comments do not work well with code)

If you want to map a double to an integer, you can use a variant record:

Beware that this does a bitwise copy without interpretation of the values.

Another (kind of dirty trick, is using absolute variables:

There’s really no need to do something like this, because the default value of GetHashCode already returns a number that’s guaranteed to be unique for each object: the object’s memory address. Furthermore, the default hash value isn’t going to change if you change the data your object contains.

Let’s say you have an object that contains a Double with a value of 3.5, and you hash it and put it into a dictionary, and you get a hash code of 12345678. You also have something else holding a reference to it, and that Double field gets changed and now it’s got a value of 5.21. Next time you attempt to calculate its hash value, your hash code is now 23456789, and your lookup will fail.

Unless you can guarantee that this will never happen, and you have a really good reason not to use the memory address, your best bet is to just leave GetHashCode as it is. (If it ain’t broke, don’t fix it.)

Best way to convert a double to an integer?

Best way to convert a double to an integer?

RE: Best way to convert a double to an integer?

RE: Best way to convert a double to an integer?

won’t trunc work?

RE: Best way to convert a double to an integer?

check the Math unit for functions floor and ceil.

depends on what delphi version you have though.

——————————————————
What You See Is What You Get
Never underestimate tha powah of tha google!

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Оцените статью