C的位域表示法unsigned char a:2

位域表示法
加类型,表示在这个类型上分配
比较:
struct packet_bit 

  unsigned char a:2; 
  unsigned char b:3; 
}bit; 
这样bit只在一个字节 unsigned char内分配,未分配3位!!szieof(bit)=1

struct packet_bit 

  unsigned int a:2; 
  unsigned int b:3; 
}bit; 
则在四字节unisgned int内分配,其它未分配的27位!!!szieof(bit)=4!

示例

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
 
typedef struct  { 
	unsigned int a : 1;  
	unsigned int b : 2;  
	unsigned int c : 3;  
}__attribute__((packed)) x;  

typedef struct  {   
	unsigned char a : 1;  
	unsigned char b : 2;  
	unsigned char c : 3;  
}__attribute__((packed)) y;  //0x1d   0001 1101

typedef struct  { 
	unsigned int a : 1;  
	unsigned int b : 1;  
	unsigned int c : 1;  
}__attribute__((packed)) z; 

typedef struct  {   
	unsigned char a1 : 1;  
	unsigned char a2 : 1;  
	unsigned char a3 : 1; 
    unsigned char a4 : 1;  
	unsigned char a5 : 1;  
	unsigned char a6 : 1; 	
	unsigned char a7 : 1;
	unsigned char a8 : 1;
}__attribute__((packed)) fota_t; 

int main()
{
	x xxx;  
	y yyy; 
	z zzz;
	fota_t fota;
	char tt[4];
	int cc=4660; //0x1234
	
	memcpy(tt,&cc,4);  //0x34,0x12,0x00,0x00
	printf("0x%x,0x%x,0x%x,0x%x\n", tt[0], tt[1], tt[2], tt[3]);
	
	//0x67
	fota.a1 = 1; // 0110 0111 
	fota.a2 = 1;  
	fota.a3 = 1; 
	fota.a4 = 0;
	fota.a5 = 0;  
	fota.a6 = 1;  
	fota.a7 = 1; 
	fota.a8 = 0;
	printf("%d<char00> 0x%x\n", sizeof(fota), fota);
	
	xxx.a = 1;  
	xxx.b = 2;  
	xxx.c = 3; 
	printf("%d<int1>%d, %d, %d\n", sizeof(xxx), xxx.a, xxx.b, xxx.c);  

    yyy.a = 1;  
	yyy.b = 2;  
	yyy.c = 3;//0x1d   0001 1101
	printf("%d<char test>%d, %d, %d,0x%x\n", sizeof(yyy), yyy.a, yyy.b, yyy.c, yyy);
	
    xxx.a = 2;  
	xxx.b = 3;  
	xxx.c = 4;  
	printf("%d<int2>%d, %d, %d\n", sizeof(xxx), xxx.a, xxx.b, xxx.c);
	
	zzz.a = 2;  
	zzz.b = 3;  
	zzz.c = 4;
	printf("%d<int3>%d, %d, %d\n", sizeof(zzz), zzz.a, zzz.b, zzz.c);
	
	zzz.a = 0xff;  
	zzz.b = 0xff; 
	zzz.c = 0xff; 
	printf("%d<int4>0x%x, 0x%x, 0x%x\n", sizeof(zzz), zzz.a, zzz.b, zzz.c);
	
	xxx.a = 0xff; 
	xxx.b = 0xff;  
	xxx.c = 0xff;
	printf("%d<int5>0x%x, 0x%x, 0x%x\n", sizeof(xxx), xxx.a, xxx.b, xxx.c);
	
	zzz.a = 3;  
	zzz.b = 4;  
	zzz.c = 5; 
	printf("%d<int6>0x%x, 0x%x, 0x%x\n", sizeof(zzz), zzz.a, zzz.b, zzz.c);
	
	return 0;
}

运行结果

0x34,0x12,0x0,0x0
1<char00> 0x67
1<int1>1, 2, 3
1<char test>1, 2, 3,0x1d
1<int2>0, 3, 4
1<int3>0, 1, 0
1<int4>0x1, 0x1, 0x1
1<int5>0x1, 0x3, 0x7
1<int6>0x1, 0x0, 0x1

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值