[英]How to read the syntax of a C++ Bitfield definition?
I need some help in understanding the syntax of a Bitfield definition.我需要一些帮助来理解位域定义的语法。 I read the Microsoft documentation page on it but the example there still leaves me with my question.
我阅读了上面的 Microsoft 文档页面,但那里的示例仍然给我留下了疑问。 Given a Bitfield and main method like this:
给定一个 Bitfield 和 main 方法,如下所示:
struct {
unsigned short character : 8;
unsigned short color : 4;
} text[80];
int main() {
text[20].character = 'a';
text[20].color = 5;
}
For better reference of what I'm asking, here numbered:为了更好地参考我的要求,这里编号:
[80]
and the [20]
's mean here? [80]
和[20]
在这里是什么意思?text[80]
mean an array of 80 such structs? text[80]
是否表示包含 80 个此类结构的数组?text[20].character = 'a'
mean, that at position 20 of the array there is a character 'a'
? text[20].character = 'a'
意味着在数组的位置 20 处有一个字符'a'
?"What do the [80]
and the [20]
's mean here?" “这里的
[80]
和[20]
是什么意思?”
text[80];
declares an array with 80 elements and text[20]
accesses the 21st element.声明一个包含 80 个元素的数组,
text[20]
访问第 21 个元素。
"Does text[80]
mean an array of 80 such structs?" “
text[80]
是否表示包含 80 个这样的结构的数组?
Yes.是的。
"Does text[20].character = 'a'
mean, that at position 20 of the array there is a character 'a'?" “
text[20].character = 'a'
意味着,在数组的第 20 位有一个字符 'a'?”
Yes.是的。
What do the [80] and the [20]'s mean here?
[80] 和 [20] 在这里是什么意思?
The [80] means defining an array of the anonymous type that you defined(the defined structure). [80] 表示定义您定义的匿名类型的数组(定义的结构)。 let me clearly tell what is happening.
让我清楚地说明正在发生的事情。 As unsigned short is 16 bits, this struct will be a 16 bits memory that first 8 bits are named as the character, and the 4 middle bits are named as color, and 4 ending bits are not used.
由于unsigned short是 16 位,因此该结构体将是一个 16 位内存,其中前 8 位命名为字符,中间 4 位命名为颜色,不使用 4 个结束位。
You created an array of 80 elements from this structure.您从此结构创建了一个包含 80 个元素的数组。 It means you have 80 consecutive 16 bit in the memory;
这意味着您的内存中有 80 个连续的 16 位; each of these elements(16 bit) has a character(8 bit) and a color(4 bit) and 4 unused bit.
这些元素(16 位)中的每一个都有一个字符(8 位)和一个颜色(4 位)和 4 个未使用的位。
Bitfield is very useful in low-level software and embedded systems.位域在低级软件和嵌入式系统中非常有用。 For example in your scenario, it seems a consumer waiting for data that its 8 first bits will be treated as a character(ASCII), and its 4 next bits are treated as the color of that character.
例如,在您的场景中,似乎消费者在等待数据,其前 8 位将被视为字符(ASCII),而其接下来的 4 位将被视为该字符的颜色。 So your 80 element array means 80 characters that have its own color.
所以你的 80 个元素数组意味着 80 个有自己颜色的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.