float-hacks icon indicating copy to clipboard operation
float-hacks copied to clipboard

The code is unportable due to datatype size assumptions

Open KarolS opened this issue 8 years ago • 1 comments

The code assumes erroneously that long and float are of the same size, but that is not the case on many architectures and makes the code broken. In particular, x64 Linux won't work.

KarolS avatar Dec 19 '16 18:12 KarolS

I commented on the Reddit thread, but I'll copy it over here for clarity.


To be fair, it doesn't matter if these two types are different sizes. The specification ensures that both views start at the same place:

The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), and vice versa.

In other words, if I have

typedef union {uint32_t u32; uint64_t u64} lens_t;
lens_t x;
x.u64 = 0xfffffff; // well above what u32 can handle

then x.u32 contains the lower 32 bits of x.u64. This is the intended behavior in our case.

I won't close this issue out in case there's something I'm overlooking here. Can you verify this from your end as well?

leegao avatar Dec 19 '16 19:12 leegao