bijesh
bijesh

Reputation: 91

value changes while reinterpret_cast

while converting an integer to float by using reinterpret_cast the content of memory changes.

For example,

   float fDest = 0;
  __int32 nTempDest = -4808638;

  fDest = *reinterpret_cast<float*>(&nTempDest);

Hexadecimal representation for the variable value nTempest is '42 a0 b6 ff' but after reinterpret_cast the content of fDest is '42 a0 f6 ff'.

Can any one could give an answer why this third byte changed from b6 to f6.

Upvotes: 3

Views: 616

Answers (2)

JoergB
JoergB

Reputation: 4443

In pure C++ this is in fact undefined behavior. Nevertheless there is an explanation for what you see.

I assume that the hexadecimal representations you give are from a bytewise view of memory. Obviously you are on a little endian architecture. So the 32-bit quantity we are starting from is 0xffb6a042, which is indeed the two's complement representation of -4808638.

As a IEC 60559 single-precision floating point number (also 32 bits) 0xffb6a042 is a negative, signaling NaN. NaNs in this representation have the form (in binary)

s1111111 1qxxxxxx xxxxxxxx xxxxxxxx

Here s is the sign, the x are arbitrary and q=1 for a quiet NaN and q=0 for a signaling NaN.

Now you are using the signaling Nan in that you assign it to fDest. This would raise a floating point invalid exception if floating point signaling is active. By default such exceptions are simply ignored and signaling NaN values are 'quieted' when propagated on.

So: In assigning to fDest, the NaN is propagated and the implementation converts it to a quiet NaN by setting bit 22. This is the change you observe.

Upvotes: 2

Alok Save
Alok Save

Reputation: 206508

Your code produces an Undefined Behavior(UB).
reinterpret_cast only gives the guarantee that if you cast from one pointer type to another and cast it back to the original pointer type then you get the original data. Anything other than that produces UB[Note 1]

This is an UB because you cannot rely on the fact that:

sizeof(float) == sizeof(nTempDest)

This is not guaranteed to be true on all implementations, definitely not true for the ones which follow strict aliasing. And if the implementation doesn't what you get is Undefined Behavior.


[Note 1]There are exceptions to this rule, if you need to rely on these corner rules, you are swimming in rough waters, So be absolutely sure of what you are doing.

Upvotes: 1

Related Questions