Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API

From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
lorentz1574116hisn'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.
-
YourMom14416h@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.
-
lorentz1574116h@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.
-
YourMom14416h@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. -
lorentz1574116h@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.
Related Rants
-
xjose97x20Just saw a variable in C named like this: long time_ago; //in a galaxy far away I laughed no stop.
-
Unskipp24So this happened last night... Gf: my favorite bra is not fitting me anymore Me: get a new one ? Gf: but it ...
-
sam966911
Hats off to this lady .... I would have just flipped the machine
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
rant
your mom
dark ages
c++