Alex Rivera | Logout

Trap representation

Asked 2011-07-17T18:22:53.873
106
  1. What is a "trap representation" in C (some examples might help)? Does this apply to C++?

  2. Given this code...

    float f=3.5;
    int *pi = (int*)&f;
    

    ... and assuming that sizeof(int) == sizeof(float), do f and *pi have the same binary representation/pattern?

Edit
Report

1 Answer

6

In general, any non-trap IEEE-754 floating point value can be represented as an integer on some platforms without any issue. However, there are floating point values that can result in unexpected behavior if you assume that all floating point values have a unique integer representation and you happen to force the FPU to load that value.

(The example is taken from Byte Swapping Floating Point Types.)

For instance, when working with floating point data you need to marshal between CPUs with different endianness, you might think of doing the following:

double swap(double)

Unfortunately, if the compiler loads the input into an FPU register and it's a trap representation, the FPU can write it back out with an equivalent trap representation that happens to be a different bit representation.

In other words, there are some floating point values that do not have a corresponding bit representation if you don't convert correctly (by correct I mean through a union, memcpy via char * or other standard mechanism).

answered 2011-07-18T19:48:03.937

Your Answer