一、大小端:
1 大端: 数据低位存放在内存高地址, 数据高位存放在内存低地址
2 小端: 数据低位存放在内存底地址, 数据高位存放在内存高地址
3 网络字节序以大端传输、主机字节序根据CPU架构不同既有大端与有小端
以联合体来做说明:
union endpoint { unsigned short n; char ch[2];};int 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;return 0;}/*
二、位域已知一个16位的整数,请按4位为一个数, 写个求和函数。如:16位整数的二进制为1101 0101 1110 0011, 计算结果为 1101 + 0101 + 1110 + 0011 = 35
*/
union endpoint { unsigned short n; char ch[2];};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);}/*三、字节对齐
* /
void main()
{ struct node { }; unsigned short n = sizeof(node); // 1 struct node1 { int a; char b; short c; }; n = sizeof(node1); //因为结构体node1中最长的数据类型是int,占4个字节,因此以4字节对齐,则该结构体在内存中存放方式为 //|--------int--------| //|char|----|--short--| // 4 + 4 = 8 struct node2 { char b; int a; short c; }; n = sizeof(node2); //因为结构体node2中最长的数据类型是int,占4个字节,因此以4字节对齐,则该结构体在内存中存放方式为 //|-------char--------| //|--------int--------| //|-------short-------| // 4 + 4 + 4= 12 struct node4 { bool a; node1 node1_; short b; }; n = sizeof(node4); //4 + 8 + 4 因为node1中最宽字段为int a, 占4字节且小于默认的8字节对齐, 所以取4byte为对齐字节 struct node5 { bool a; node1 nodde_; char d; double b; char c; }; n = sizeof(node5); //8 + 8 + 8 + 8 + 8 = 40#PRagma pack(4) struct node6 { bool a; node1 nodde_; char d; double b; char c; }; n = sizeof(node6); //4 + 8 + 4 + 8 + 4 = 28#pragma pack()}
新闻热点
疑难解答