help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: int/float binary conversion


From: Lars Christian Jensen
Subject: Re: int/float binary conversion
Date: Thu, 15 Sep 2005 09:14:46 +0200


On Wed, 14 Sep 2005, Ulrich Eckhardt wrote:

Lars Christian Jensen wrote:
    float f1 = 4.5;
    int i =    *((int*)&f1);
    float f2 = *((float*)&i);

    printf("f1 = %f, i = 0x%08x, f2 = %f\n", f1, i, f2);

You are using stupid, brute force casts to convert between totally
unrelated objects and expect anything useful?

Assume that sizeof(int) == sizeof(float), which is the case on my platform. The binary representation of the float is put into an integer (the integer value would of course be platform dependent), and then back into another float. I would assume that those two floats should have the same binary representation, and hence have the same value, but they don't.

Sorry, but what exactly is your problem?

I found an equivalent c-style cast that caused problems inside a library that used to work. A float/int union solves the problem (and is easier to read), but I can't see anything wrong in these casts.

If you wanted to demonstrate that it is possible to write C++ programs that don't behave consistently (i.e. show different implementations of 'undefined behaviour'), fine, but we all knew that already.

The problem code uses pointer-to-pointer c-style casts, address-of operator(&) and indirection operator(*). Which of these gives un-defined behaviour in c++?

--
Lars Christian Jensen


reply via email to

[Prev in Thread] Current Thread [Next in Thread]