为长度为1的位域分配一个值 [英] Assigning a value to bitfield with length 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
.因此,这让我认为,将数字分配给单个位字段会得到最低有效位(2
是10
(二进制),3
是11
).
two
will contain 0
s in its fields, while three
will contain 1
s. 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?
注意:通过分配0
和1
,而不是分别分配2
和3
,可以实现相同的结果.我使用2
和3
只是为了说明我的问题,我不会在现实世界中使用它
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.而且,是的,我对C
和C++
都很感兴趣,请不要告诉我它们是不同的语言,因为我知道这一点:)
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屋!