65,211
社区成员
发帖
与我相关
我的任务
分享
int main()
{
typedef struct bitstruct
{
unsigned int b1:5; /* 用unsigned测试,容易理解一点 */
unsigned int :2;
unsigned int b2:2;
} bitstruct;
typedef union {
unsigned char c[4];
bitstruct bs;
} unionbits;
unionbits bits={0};
bits.c[0]=0x15; /* 修改c[0]即修改前8个bit,看b1,b2的值,就知道分布了 */
cout<<hex<<"b1="<<bits.bs.b1<<endl<<"b2="<<bits.bs.b2<<endl;
return 0;
}
写成代码楼主自己看
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
typedef struct bitstruct
{
int b1:5;
int :2;
int b2:2;
} bitstruct;
unsigned char buf[]={0xB0, 0xB1, 0xB2, 0xB3};
bitstruct test;
memcpy(&test,buf,4);
cout<<test.b1<<endl;
cout<<test.b2<<endl;
unsigned char ch='e';
memcpy(&test,&ch,1);
cout<<test.b1<<endl;
cout<<test.b2<<endl;
return 0;
}