Little endian Vs Big endian

后端 未结 5 1478
北海茫月
北海茫月 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 11:07

    If you really want to convert an int to a short, then just do that:

    short int_to_short(int n) {
      if (n < SHRT_MIN) return SHRT_MIN;
      if (n > SHRT_MAX) return SHRT_MAX;
      return (short)n;
    }
    

    You don't have to even worry about endian, the language handles that for you. If you are sure n is within the range of a short, then you can skip the check, too.

提交回复
热议问题