位段是C语言中使用较少的一种特殊的结构体,C语言允许在一个结构体中以位为单位来指定其成员所占内存长度,这种以位为单位的成员称为“位段”或称“位域”( bit field) 。利用位段能够用较少的位数存储数据。
struct packed-data { unsigned a:2; unsigned b:6; unsigned c:4; unsigned d:4; int i; }data;其内存分配的结构如下所示
利用位段结构体,可以实现数据的统计信息。
参考题目:1的个数
题目分析,本题很显然就是要求统计输入整数的1的个数问题,当然,这题也可以使用位运算进行统计,在这里,我们使用位段进行结题。
可知,输入的数据N<=1000<2^16,所以设计16位的结构体位段
typedef struct A { unsigned short a0:1; unsigned short a1:1; unsigned short a2:1; unsigned short a3:1; unsigned short a4:1; unsigned short a5:1; unsigned short a6:1; unsigned short a7:1; unsigned short a8:1; unsigned short a9:1; unsigned short a10:1; unsigned short a11:1; unsigned short a12:1; unsigned short a13:1; unsigned short a14:1; unsigned short a15:1; }DATATYPE;
接着,就想办法将整数转换到位段中去,直接赋值肯定是错的,使用每一位赋值,要求用到位运算,复杂而为容易出错,这里,我们要使用一个内存拷贝函数memcpy(void*,void*,size_t)
其实无论是结构体、数组、还是int变量,归根结底还是要在内存中连续表示,memcpy函数能实现数据得拷贝,是基于内存级别的。
参考源码:
#include <memory.h> #include <iostream> using namespace std; #define sums(b) b.a0+b.a1+b.a2+b.a3+b.a4+b.a5+b.a6+b.a7+ b.a8+b.a9+b.a10+b.a11+b.a12+b.a13+b.a14+b.a15 typedef struct A { unsigned short a0:1; unsigned short a1:1; unsigned short a2:1; unsigned short a3:1; unsigned short a4:1; unsigned short a5:1; unsigned short a6:1; unsigned short a7:1; unsigned short a8:1; unsigned short a9:1; unsigned short a10:1; unsigned short a11:1; unsigned short a12:1; unsigned short a13:1; unsigned short a14:1; unsigned short a15:1; }DATATYPE; int main(int argc ,char** argv) { DATATYPE p; int c; int n; //scanf("%d",&n); cin>>n; while(n) { unsigned short b; n--; cin>>b; memcpy(&p,&b,sizeof(short)); c=sums(p); cout<<c<<endl; } return 0; }
原文地址:http://blog.csdn.net/u011889952/article/details/44860845