位域结构体

        有时候在通信时仅代表一个bool型的量,不需单独占用一个byte,通过定义位域结构体可以将若干个变量放到一个byte里,一个变量占用若干bits(小于8),这样就能节省很多空间,例如:

1
2
3
4
5
typedef struct BITSTRUCT{
int A:2;
int B:5;
int C:1;
}BitStruct;

        以64位X86上的Ubuntu16.04为例,这样一个BitStruct的结构体一共使用了一个Byte的空间,其中A占了低端的2bit,B占了中间的5bit,C占了最高的1bit:

bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
C B A

联合体

       但也有一些情况比如一个长度的变量占用了4个byte,每次解析时都通过左移、右移也很麻烦,这样就可以通过联合体来包含一个结构体,在这个联合体中定义一个long int的长整型,然后同时再在这个联合体了放一个包含4个byte的结构体,这样就可以用来拼接字符串进行消息通信了:

1
2
3
4
5
6
7
8
9
typedef union UNIST{
long int nTotal;
struct{
char c1;
char c2;
char c3;
char c4;
}cSep;
}UniSt;

下面是一段代码供参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#pragma pack(8)

typedef unsigned char BYTE;
typedef unsigned short int WORD;
typedef unsigned long int DWORD;

typedef union {
DWORD head;
struct {
DWORD a:6;
DWORD b:6;
DWORD c:6;
DWORD d:6;
DWORD e:6;
DWORD f:2;
}headst;
}uHead;
typedef union {
WORD end;
struct {
WORD a:5;
WORD b:2;
WORD c:7;
WORD d:2;
}endst;
}endst;

typedef struct {
uHead head;
BYTE len;
BYTE end;
}First;


int main()
{
int n;
BYTE orig[8];
First mf;
mf.head.headst.a=33;
mf.head.headst.b=36;
mf.head.headst.c=39;
mf.head.headst.d=49;
mf.head.headst.e=55;
mf.head.headst.f=2;
mf.len=18;
mf.end=22;
memcpy(&orig,&mf,8);
for(n=0;n<8;n++)
printf("%d-",orig[n]);
printf("\n");
printf("head=0x%x,int:%lu\n",mf.head.head,mf.head.head);
return 0;
}

输出如下

33-121-198-183-18-22-92-183-

head=0xb7c67921,int:3083237665