是什么在结构声明冒号的意思,如:1,7,16,还是32? [英] What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?

查看:162
本文介绍了是什么在结构声明冒号的意思,如:1,7,16,还是32?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是下面的C ++ code是什么意思?

What does the following C++ code mean?

unsigned char a : 1; 
unsigned char b : 7;

我想它会创建两个char 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是比特大小限制值的范围。他们通常在结构和联合发现。例如,在某些系统上(取决于字符宽度和包装规则等)时,code:

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 7位B

典型地用C用于访问COM pressed值,诸如一4位半字节可能被包含在一个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]

Bit-fields [class.bit]

形式的成员声明符

     identifieropt   attribute-specifieropt   :   constant-ex$p$pssion

     identifieropt   attribute-specifieropt   :   constant-expression

指定位字段;它的长度是从位字段名称由冒号掀起。可选的属性符的appertains所声明的实体。位字段属性是不是类成员的类型的一部分​​。

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.

恒定前pression 的应是一个积分常数前pression具有大于或等于零的值。积分常数前pression的值可以比在重新比特字段的类型的presentation对象的比特数大;在这种情况下,额外的位用作填充比特和不参与重新位字段的presentation值

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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