#include "stdafx.h"
#include <iostream>
#include <vector>
#include <cstdlib>
int _tmain(int argc, _TCHAR* argv[])
{
//std::vector<char> vec;
//vec.resize(10);
//strcpy(&vec[0], "helloword");
//std::cout << (&vec[0]);
//std::vector<char> vec2;
//std::vector<char> vec3;
//vec.swap(vec2);
//vec3.assign(vec2.rbegin(),vec2.rend());
//std::cout << vec.size();
//std::cout <<vec2.size();
//std::cout <<vec3.size();
struct prodata{
unsigned int magic_num:32;
unsigned int seq_id:32;
unsigned int trand_type:1;
unsigned int class_type:15;
unsigned int sub_class_type:16;
unsigned int response_code:16;
unsigned int crypt:2;
unsigned int zip:2;
unsigned int trans_code:4;
unsigned int padding:8;
unsigned int proto_size:32;
unsigned int checksum:32;
prodata(){Reset();}
void Reset(){*(unsigned int*)this = 0;}
}data,*pdata;
data.checksum = 21;
data.trand_type = 1;
data.class_type = 2;
data.sub_class_type = 3;
//1000 0000 0000 0010 0000 00000 0000 0011
// 80 02 00 03
unsigned int type = (data.trand_type << 31)|(data.class_type <<16)|data.sub_class_type;
data.response_code = 6;
data.crypt = 1;
data.zip = 1;
data.trans_code = 1;
data.padding = 8;
// 0000 0000 0000 0110 0101 0001 0000 1000
// 00 06 51 08
// 08 51 06 00
unsigned int status = (data.response_code << 16)|(data.crypt << 14)|(data.zip << 12)|(data.trans_code << 8) | data.padding;
std::cout <<type;
system("pause");
return 0;
1. 一个位域必须存储在定义它的一个数据类型内部,不能跨跨该数据类型。如char定义的位域所剩空间不够存放另一位域时,应从下一单元起存放该位域。也可以有意使某位域从下一单元开始。
2.由于位域不允许越过定义它的数据类型,因此位域的长度不能大于定义它的数据类型的长度。
3. 位结构总长度(位数), 是各个位成员定义的位数之和再向最大结构成员对齐。
4. 位结构成员可以与其它结构成员一起使用。
struct A
{
char c1:1;
char c2:3;
unsigned short s2:13;
unsigned long i:3;
};
printf(“%d\n”, sizeof(struct A));
c1和c2占用相同的一个字节,s2占2个字节,s2可以表示16位,i占4字节,加起来是7字节,由于结构体要对齐,所以是8个字节;
在基于tcp的网络开发中,特别是在存在自定义的二进制协议的情况下,位域的操作就很重要了。
在select io模型中可以根据先定义好位域,然后根据响应的事件,触发操作。
另外在tcp的网络编程中,网络框架需要维护对每一个socket维护一个输入和一个输出buffer。这个buffer的主要作用是缓冲数据,操作系统的内核在tcp的实现上游自己的缓冲,
如对上层来说一次发送很大的数据,网络库在条用send发送操作系统可接受的字节后,需缓存未发送的。读数据同样的道理。