一、大小端:
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()}
新聞熱點
疑難解答