Programmers should strive to make their programs portable across different machines and compilers.
For program objects that span multiple bytes, we must establish two conventions: what will be the address of the object, and how will we order the bytes in memory. In virtually all machines, a multibyte object is stored as a contiguous sequence of bytes, with the address of object given by the smallest address of the bytes used.
For example, suppose a variable x of type int has value of 0x01234567, has address 0x100. Then the four bytes of x would be stored in memory locations 0x100, 0x101, 0x102, and 0x103. We can store 0x01234567 in momory from the least significant byte to most, neither from most to least. In the real world, there includes this two former convention.
Where the least significant byte comes first----is referred to as little endian.
Where the most significant byte comes first----is referred to as big endian.
Big endian
* 0x100 0x101 0x102 0x103
* 01 23 45 67
little endian
* 0x100 0x101 0x102 0x103
* 67 45 23 01
This is just a convension, not good or bad between them. Be careful in network programming. If you want to keep correct between machines with diffrent byte ordering, please tranfer to network byte ordeing before communication.
If you want know what the byte order of your machine, using the code scenario below here. the output is "11" means little endian, the output is "ff" means big endian.
#include <stdio.h>
union endian
{
char a;
int i;
};
int main(int argc, char* argv[])
{
endian t;
t.i = 0xffaabb11;
本文探讨了在不同机器和编译器间保持程序可移植性的重要性,并详细介绍了字节序的概念及其在网络编程中的应用。文章解释了小端字节序(little endian)和大端字节序(big endian)的区别,并提供了一个简单的代码示例来检测当前机器的字节序。
1万+

被折叠的 条评论
为什么被折叠?



