by blorsh · 8y ago · 0 comments
The standard only allows reading a value as the type it was written with or as char, and an access as char is only good for copying. If a char access used different bit order, that would be OK according to the standard because you couldn't tell unless you violated the standard.
It seems every compiler will tolerate a memcpy for type punning, even though this isn't required.
Having said that, it is possible to implement memcopy in standard C: char pointers have an explicit special exemption to the aliasing rule so you are allowed to inspect objects as array of chars.
double d = 3.14;
uint64_t i;
memcpy(&i, &d, sizeof(d));
is perfectly kosher.Aren't exact-bitwidth integer types optional even with C99 (let alone preceding versions of standard)?
If an implementation can't represent uint64_t exactly, it can still have a uint_least64_t type of whatever width works.
a) I believe sizeof (double) * 8 == 64 is not enforced by the standard either. One could argue that it is hard to find anything else these days, but (for a contrived example) I believe nothing prevents you from making your own port of GCC for some purpose, and make 'double' be 'float'. (From my memories, it is even far enough from rocket science.)
b) It already happened to me personally, to work with code where people have implemented their own uintXX types (because of the lack of the standard ones), and then over time these became narrower/vider.
So if we would like to have it portable, I think, nothing beats:
union { double d; char cc [sizeof (double)]; };
and there we are, back to what is in the standard.