little endian & big endian (record)

本文探讨了在不同机器和编译器间保持程序可移植性的重要性,并详细介绍了字节序的概念及其在网络编程中的应用。文章解释了小端字节序(little endian)和大端字节序(big endian)的区别,并提供了一个简单的代码示例来检测当前机器的字节序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

printf("%p/n", t.a);
return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值