问题描述
以下 C++ 代码是什么意思?
What does the following C++ code mean?
unsigned char a : 1;
unsigned char b : 7;
我猜它创建了两个字符 a 和 b,它们都应该是一个字节长,但我不知道:1"和:7"部分的作用.
I guess it creates two char a and b, and both of them should be one byte long, but I have no idea what the ": 1" and ": 7" part does.
推荐答案
1 和 7 是位大小,用于限制值的范围.它们通常出现在结构和工会中.例如,在某些系统上(取决于 char
宽度和打包规则等),代码:
The 1 and the 7 are bit sizes to limit the range of the values. They're typically found in structures and unions. For example, on some systems (depends on char
width and packing rules, etc), the code:
typedef struct {
unsigned char a : 1;
unsigned char b : 7;
} tOneAndSevenBits;
创建一个 8 位值,a
为 1 位,b
为 7 位.
creates an 8-bit value, one bit for a
and 7 bits for b
.
通常在 C 中用于访问压缩"值,例如 4 位 nybble,它可能包含在 8 位字符的上半部分:
Typically used in C to access "compressed" values such as a 4-bit nybble which might be contained in the top half of an 8-bit char:
typedef struct {
unsigned char leftFour : 4;
unsigned char rightFour : 4;
} tTwoNybbles;
对于我们中间的语言律师来说,C++11 标准的 9.6 部分详细解释了这一点,稍微转述一下:
For the language lawyers amongst us, the 9.6 section of the C++11 standard explains this in detail, slightly paraphrased:
位域 [class.bit]
表单的成员声明符
标识符 属性说明符 : 常量表达式
identifier attribute-specifier : constant-expression
指定一个位域;它的长度由冒号从位域名称开始.可选的 attribute-specifier 属于被声明的实体.位域属性不是类成员类型的一部分.
specifies a bit-field; its length is set off from the bit-field name by a colon. The optional attribute-specifier appertains to the entity being declared. The bit-field attribute is not part of the type of the class member.
constant-expression 应该是一个整数常量表达式,其值大于或等于零.整数常量表达式的值可能大于位域类型的对象表示中的位数;在这种情况下,额外的位用作填充位,不参与位域的值表示.
The constant-expression shall be an integral constant expression with a value greater than or equal to zero. The value of the integral constant expression may be larger than the number of bits in the object representation of the bit-field’s type; in such cases the extra bits are used as padding bits and do not participate in the value representation of the bit-field.
类对象内的位域分配是实现定义的.位域的对齐是实现定义的.位域被打包到一些可寻址的分配单元中.
Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit.
注意: 位域在某些机器上跨越分配单元,而在其他机器上则不跨越.位域在某些机器上从右到左分配,在其他机器上从左到右分配.- 结束说明
Note: bit-fields straddle allocation units on some machines and not on others. Bit-fields are assigned right-to-left on some machines, left-to-right on others. - end note
这篇关于结构声明中的冒号是什么意思,例如:1、:7、:16 或:32?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!