为长度为1的位域分配一个值 [英] Assigning a value to bitfield with length 1

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

问题描述

假设我有

struct A
{
    signed char a:1;
    unsigned char b:1;
};

如果我有

A two, three;
two.a = 2; two.b = 2;
three.a = 3; three.b = 3;

two在其字段中将包含0,而three将包含1.因此,这让我认为,将数字分配给单个位字段会得到最低有效位(210(二进制),311).

two will contain 0s in its fields, while three will contain 1s. So, this makes me think, that assigning a number to a single-bit-field gets the least significant bit (2 is 10 in binary and 3 is 11).

所以,我的问题是-这是正确且跨平台的吗?还是取决于机器,编译器等.标准是否对此有所说明,或者完全由实现定义?

So, my question is - is this correct and cross-platform? Or it depends on the machine, on the compiler, etc. Does the standard says anything about this, or it's completely implementation defined?

注意:通过分配01,而不是分别分配23,可以实现相同的结果.我使用23只是为了说明我的问题,我不会在现实世界中使用它

Note: The same result may be achieved by assigning 0 and 1, instead of 2 and 3 respectively. I used 2 and 3 just for illustrating my question, I wouldn't use it in a real-world situation

P.S.而且,是的,我对CC++都很感兴趣,请不要告诉我它们是不同的语言,因为我知道这一点:)

P.S. And, yes, I'm interesting in both - C and C++, please don't tell me they are different languages, because I know this :)

推荐答案

这种情况下的规则与全角算术没有什么不同.位域的行为与相应的全尺寸类型相同,不同之处在于位域的宽度受您在位域声明(C99中的6.7.2.1/9)中指定的值限制.

The rules in this case are no different than in case of full-width arithmetic. Bit-fields behave the same way as the corresponding full-size types, except that their width is limited by the value you specified in the bit-field declaration (6.7.2.1/9 in C99).

将溢出的值分配给带符号的位域会导致实现定义的行为,这意味着您使用位域a观察到的行为通常是不可移植的.

Assigning an overflowing value to a signed bit-field leads to implementation-defined behavior, which means that behavior you observe with bit-field a is generally not portable.

将溢出值分配给无符号位域使用模算术规则,这意味着该值以模数2^N取,其中N是位域的宽度.例如,这意味着将偶数分配给您的位域b将始终产生值0,而将奇数分配给该位域将始终产生1.

Assigning an overflowing value to an unsigned bit-field uses the rules of modulo arithmetic, meaning that the value is taken modulo 2^N, where N is the width of the bit-field. This means, for example, that assigning even numbers to your bit-field b will always produce value 0, while assigning odd numbers to such bit-field will always produce 1.

这篇关于为长度为1的位域分配一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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