Jsk
Jsk

Reputation: 179

Converting integer to floating point number in Delphi

Could someone please explain the below code to me? It takes the Integer and converts it to a Single floating point number but if someone could break this down and elaborate that would be helpful.

singleVar := PSingle(@intVar)^

Upvotes: 0

Views: 870

Answers (1)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 109003

This doesn't convert the integer to a float. It reinterprets the bytes of the 32-bit integer as a single (a floating point data type that also has 32 bits).

@intVar is the address of the integer data in memory. The type is pointer to integer (PInteger). By writing PSingle(@intVar), you tell the compiler to pretend that it is a pointer to a single; in effect, you tell the compiler that it should interpret the data at this place in memory as a single. Finally, PSingle(@intVar)^ is simply dereferencing the pointer. Hence, it is the "single" value at this location in memory, that is, the original bytes now interpreted as a single.

Interpreting the bytes of an integer as a single doesn't give you the same numerical value in general. For instance, if the integer value is 123, the bytes are 7B00 0000. If you interpret this sequence of bytes as a single, you obtain 1,72359711111953E-43 which is not numerically equivalent.

To actually convert an integer to a single, you would write singleVar := intVar.

Upvotes: 4

Related Questions