4 ms·
typedef union { struct { uint64_t fraction : 52; uint32_t exp_bias : 11; uint32_t sign : 1; } fields; double value;
by CyberRabbi 5y ago
typedef union {
struct {
uint64_t fraction : 52;
uint32_t exp_bias : 11;
uint32_t sign : 1;
} fields;
double value;
} binary64_float;
Accessing the value stored in "value" through the "fields" member is undefined behavior. I'm legitimately surprised that lemire published this code. The correct and well-defined way to do this is to memcpy() the double value to a char array and access the relevant bits that way.
- Cloudef 5y agoIts not, union is valid in C(note, not c++) for this.
- nly 5y agoIt is probably still unwise in C as well in this case because the layout of bits in a bitfield is still implementation defined, and varied based on endianness of the uint64 for example
- occamrazor 5y agoWhat is the alternative? Are there functions in the C standard to get mantissa and exponent?
- gpderetta 5y agoFrexp modf. Last time I checked code generation wasn't particularly good.
- CyberRabbi 5y agoI already mentioned the alternative. memcpy() into a char array.
- Cloudef 5y agoMemcpy doesnt fix endianess
- CyberRabbi 5y agoIt was never claimed to deal with endianness and while we're on the subject of binary-layout, union-based binary manipulation is even worse on that front as no specific binary layout is mandated for structures or floating points.
- CyberRabbi 5y agolemire's code is C++
- chrisseaton 5y ago> Accessing the value stored in "value" through the "fields" member is undefined behavior. I’m surprised at that. Can you quote the relevant part of the spec that you think makes this undefined behaviour?
- CyberRabbi 5y agoIt's undefined behavior in C++. In C it is not certain if it is undefined or unspecified behavior. https://stackoverflow.com/questions/11373203/accessing-inactive-union-member-and-undefined-behavior https://stackoverflow.com/questions/11373203/accessing-inact...
- chrisseaton 5y agoI think the standard and the link you've giving makes it pretty explicit that it's unspecified. I don't really see where you can get undefined from?