一、大小端:
1 大端: 数据低位存放在内存高地址, 数据高位存放在内存低地址
2 小端: 数据低位存放在内存底地址, 数据高位存放在内存高地址
3 网络字节序以大端传输、主机字节序根据CPU架构不同既有大端与有小端
4. 如何轻松记住大端小端(引用自:http://www.cnblogs.com/wuyuegb2312/archive/2013/06/08/3126510.html)
在裘宗燕翻译的《程序设计实践》里,这对术语并没有翻译为“大端”和小端,而是“高尾端”和“低尾端”,这就好理解了:如果把一个数看成一个字符串,比如11223344看成"11223344",末尾是个'\0','11'到'44'个占用一个存储单元,那么它的尾端很显然是44,前面的高还是低就表示尾端放在高地址还是低地址,它在内存中的放法非常直观,如下图:
(数据看成字符串)大端——高尾端,小端——低尾端
以联合体来做说明:
union endpoint {
unsigned short n;
char ch[2];
};
int main()
{
endpoint endpoint_t;
endpoint_t.n = 0x1122;
if (endpoint_t.ch[0] == 0x11 && endpoint_t.ch[1] == 0x22)
std::cout << "big ending" << std::endl;
else
std::cout << "little ending" << std::endl;
return 0;
}
二、位域已知一个16位的整数,请按4位为一个数, 写个求和函数。如:16位整数的二进制为1101 0101 1110 0011, 计算结果为 1101 + 0101 + 1110 + 0011 = 35
typedef struct set_ {
#ifndef __LITTLE_ENDING__
unsigned short a : 4;
unsigned short b : 4;
unsigned short c : 4;
unsigned short d : 4;
#else
unsigned short c : 4;
unsigned short d : 4;
unsigned short a : 4;
unsigned short b : 4;
#endif
}set_t;
unsigned short binset_plus(const unsigned short n)
{
set_t s = { 0 };
memcpy(&s, &n, sizeof(short));
return s.a + s.b + s.c + s.d;
}
void main()
{
endpoint endpoint_t;
endpoint_t.n = 0x1122;
if (endpoint_t.ch[0] == 0x22 && endpoint_t.ch[1] == 0x11)
std::cout << "little ending" << std::endl;
else
std::cout << "big ending" << std::endl;
unsigned short n = 0xD5E3; // 1101 0101 1110 0011
unsigned short na = binset_plus(n);
}
三、字节对齐
传送门: C语言字节对齐问题详解