Is it safe to detect endianess with union?

后端 未结 3 822
陌清茗
陌清茗 2021-01-11 18:28

In other words, according to the C standard, is this code safe? (Assume uint8_t is one byte)

void detectEndianness(void){
    u         


        
3条回答
  •  星月不相逢
    2021-01-11 19:02

    There is no requirement that the order of bits within a byte match the ordering of the corresponding bits in a larger type. A conforming implementation which defines uint32_t and has an 8-bit unsigned char could, for example, store the upper 16 bits of the uint32_t using four bits from each byte, and store the bottom 16 bits using the remaining four bits of each byte. From the point of view of the Standard, any of 32! permutations of bits would be equally acceptable.

    That having been said, any implementation that isn't being deliberately obtuse and is designed to run on a commonplace platform will use one of two orderings [treating bytes as groups of 8 consecutive bits, in the order 0123 or 3210], and one that doesn't use one of the above and targets any platform that isn't totally obscure will use 2301 or 1032. The Standard doesn't forbid other orderings, but failure to accommodate them would be very unlikely to cause any trouble except when using obtusely-contrived implementations.

提交回复
热议问题