尚未提及的一点是,该标准明确允许整数表示可能包含填充位的可能性。就我个人而言,我希望标准委员会允许程序以一种简单的方式来指定某些预期的行为,并要求任何编译器要么遵守这些规范,要么拒绝编译;以“整数不得具有填充位”规范开头的代码将有权假设是这种情况。
As it is, it would be perfectly legitimate (albeit odd) for an implementation to store 35-bit long
values as four 9-bit characters in big-endian format, but use the LSB of the first byte as a parity bit. Under such an implementation, storing 1
into a long
could cause the parity of the overall word to become odd, thus compelling the implementation to store a 1
into the parity bit.
To be sure, such behavior would be odd, but if architectures that use padding are sufficiently notable to justify explicit provisions in the standard, code which would break on such architectures can't really be considered truly "portable".
The code using union
should work correctly on all architectures which can be simply described as "big-endian" or "little-endian" and do not use padding bits. It would be meaningless on some other architectures (and indeed the terms "big-endian" and "little-endian" could be meaningless too).