在未位域predictable答案 [英] unpredictable answer in bitfield

查看:133
本文介绍了在未位域predictable答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您给explane我为什么这个code的输出为12(1100B)

和的sizeof(第1位)是如何??? 4字节

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
结构位域
  {
   无符号的一个:5;
   无符号C:5;
   无符号乙:6;  };无效的主要()
{ 字符* P;
 结构位域位1 = {1,3,3}; // A = 00001,C = 00011,B = 000011
 P =&放大器;第1位; // p获得第1位的地址
 p ++; // incriment的p在1地址 的printf(%d个\\ N,* P); 的printf(%d个\\ N的sizeof(第1位));
}


解决方案

您已经声明的位字段无符号。在大多数现代系统,这是一个32位整数。 (无符号短为16,8字符,长度为64个等)所以,你宣布一个32位域容器。每个单独的比特字段参数的大小由位域名称之后的整数给出,但它们被装在容器的尺寸是指定的数据类型的倍数......通常的最小倍数的总指示的比特的数量将适合 - 尽管单词边界和其他东西将发挥成

我很惊讶,其余任何的很好的工作。除了在指针铸造的问题,与printf正在打印整个字段...单个字符的前8位。这不会打破该位域本身,而是字节/字符内存的边界上。根据您的系统是大端或小端,这将是MSB或LSB整场。

Could you please explane to me why the output of this code is 12 (1100b)

and how the sizeof(bit1) is 4byte???

#include <stdio.h>
#include <stdlib.h>
struct bitfield
  {
   unsigned a:5;
   unsigned c:5;
   unsigned b:6;

  };

void main()
{

 char *p;
 struct bitfield bit1={1,3,3};  //a=00001 ,c=00011 ,b=000011
 p=&bit1;                           // p get the address of bit1
 p++;                               // incriment the address of p in 1

 printf("%d\n",*p); 

 printf("%d\n",sizeof(bit1));            
}

解决方案

You have declared your bit fields as unsigned. On most modern systems, that's a 32 bit integer. (unsigned short is 16, char 8, long 64, etc.) So, you're declaring a 32 bit bitfield container. The size of each individual bit field argument is given by the integer after the bitfield name, but the size of the container they are packed in is a multiple of the data type specified... typically the smallest multiple the total indicated number of bits will fit in -- though word boundaries and other things will play into that.

I'm surprised any of the rest of it works at all. Aside from the casting issues in the pointer, the printf is printing the first 8 bits of the entire field... a single char. That will not break on the bit fields themselves, but on the byte/char memory boundary. Depending on whether your system is big endian or little endian, it will be either the MSB or LSB of the entire field.

这篇关于在未位域predictable答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆