2
YourMom
19h

I feel like working with embedded compilers is like working in the dark ages sometimes. I end up doing things that are like black magic to just make things work:

union {
float infloat;
uint32_t outint;
} puneit;

As long as the compiler supports C99 this is supposed to work. I think even if you are using it as a C++ compiler. There is also no way for us to get a compiler from the vendor for our embedded chips to do this the C++ 20 way:

float ieee_float(uint32_t f)
{
return std::bit_cast<float>(f);
}

I am not even sure if the compiler I am using is C++ 11 compatible.

edit: okay, it supports C++ 11

Comments
  • 4
    isn't it UB to read a variant other than whatever was last written? I thought that was a key feature of unions; they don't limit how each of the variants can be optimized.
  • 1
    @lorentz yes, that is why this shit is black magic. It depends upon the standard and the compiler. C99 allows it IIRC, but C++11 does not. Yet many compilers silently support it. The proper way is probably memcpy.
  • 1
    @YourMom I think C++ has a special category for types that have a meaningful value for every bit combination in their memory area so assigning them via bit cast produces an unspecified value but not UB. It includes integers, but I actually don't think it includes float, so you couldn't perform this cast in the other direction.
  • 2
    @lorentz so is the whole reason C++ has these rules and definitions is to create a language that isn't making assumptions about architecture? It seemed like certain things were UB because some future architecture it might fail on?

    I guess I don't see why a 32 bit int can't be readily mapped to a 32 bit float. I don't think float will ever be anything other than a 32 bit float. uint32_t will always be a 32 bit int. Which both are 4 bytes. Yes this assumes bytes are 8 bit. But I don't see that changing any time soon either.
  • 2
    @YourMom the widths are actually cemented in the standard. I think the reason why float isn't considered a bijection to its bit sequence is that implementations are allowed to repurpose NaN payloads for optimization.
Add Comment