位域概念 [英] Concept of bit field

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

问题描述

struct A
{
 int a:2;
 int b:3;
 int c:3;
};

int main()
{
 struct A p = {2,6,1};
 printf("\n%d\n%d\n%d\n",p.a,p.b,p.c);
 return 0;
}    

输出为:
    -2,-2,1

Output is: -2,-2,1

将上面什么code的输出用C编译器和C ++编译器?
为什么?

What would be output of above code in C complier and in C++ complier? And Why?

推荐答案

现在让我们来看看究竟发生了什么。让我们开始给定的code:

Now Lets see what exactly is happening. Lets start with the given code:

struct A
{
 int a:3;
};
int main()
{
 struct A p = {5};
 printf("%d",p.a);
}

3位中的值是101(5),因为这3位设置的符号位为1因而负值。因此,我们需要找到2的101恭维这将是011(3)。
因此,通过应用上述我们会为-3输出逻辑。同样其他可以证明。

within 3 bits the values would be 101(5) since sign bit of this 3 bit set is 1 thus negative value. Thus we need to find 2's compliment of 101 which would be 011(3). Thus by applying above logic we would output as -3. Similarly others could be proved.

例如。 1001(9),我们应采取,因为一个3位值:3。因此这将是001(1)。由于这里签位没有设置,即1所以没有必要使用2的补。直截了当的答案是1。
同样别人可以做的。

e.g. for 1001(9) we shall take 3 bit values because of a:3. thus it would be 001(1). Since here sign bit is not set i.e. 1 so no need to use 2's complement. Straight forward answer would be 1. Similarly others could be done.

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

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