int to char casting

前端 未结 4 1618
鱼传尺愫
鱼传尺愫 2020-12-16 18:41
int i = 259;       /* 03010000 in Little Endian ; 00000103 in Big Endian */
char c = (char)i;  /* returns 03 in both Little and Big Endian?? */

In

4条回答
  •  清酒与你
    2020-12-16 19:20

    If you want to test for little/big endian, you can use a union:

    int isBigEndian (void)
    {
        union foo {
            size_t i;
            char cp[sizeof(size_t)];
        } u;
    
        u.i = 1;
        return *u.cp != 1;
    }
    

    It works because in little endian, it would look like 01 00 ... 00, but in big endian, it would be 00 ... 00 01 (the ... is made up of zeros). So if the first byte is 0, the test returns true. Otherwise it returns false. Beware, however, that there also exist mixed endian machines that store data differently (some can switch endianness; others just store the data differently). The PDP-11 stored a 32-bit int as two 16-bit words, except the order of the words was reversed (e.g. 0x01234567 was 4567 0123).

提交回复
热议问题