Copying a 4 element character array into an integer in C

后端 未结 6 1766
一个人的身影
一个人的身影 2020-12-17 23:00

A char is 1 byte and an integer is 4 bytes. I want to copy byte-by-byte from a char[4] into an integer. I thought of different methods but I\'m getting different answers.

6条回答
  •  自闭症患者
    2020-12-17 23:28

    Both are correct in a way:

    • Your first solution copies in native byte order (i.e. the byte order the CPU uses) and thus may give different results depending on the type of CPU.

    • Your second solution copies in big endian byte order (i.e. most significant byte at lowest address) no matter what the CPU uses. It will yield the same value on all types of CPUs.

    What is correct depends on how the original data (array of char) is meant to be interpreted.
    E.g. Java code (class files) always use big endian byte order (no matter what the CPU is using). So if you want to read ints from a Java class file you have to use the second way. In other cases you might want to use the CPU dependent way (I think Matlab writes ints in native byte order into files, c.f. this question).

提交回复
热议问题