Little endian Vs Big endian

后端 未结 5 1475
北海茫月
北海茫月 2021-02-01 10:32

Lets say I have 4Byte integer and I want to cast it to 2Byte short integer. Am I right that in both (little and big endian) short integer will consist of 2 least significant by

5条回答
  •  北海茫月
    2021-02-01 10:59

    You should be aware that your second example

    int i = some_number;  
    short s = *(short*)&i;
    

    is not valid C code as it violates strict aliasing rules. It is likely to fail under some optimization levels and/or compilers.

    Use unions for that:

    union {
       int   i;
       short s;
    } my_union;
    
    my_union.i = some_number;
    printf("%d\n",my_union.s);
    

    Also, as others noted, you can't assume that your ints will be 4 bytes. Better use int32_t and int16_t when you need specific sizes.

提交回复
热议问题