C语言 在 C 中使用 : 运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3305933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use of the : operator in C
提问by Russel
Possible Duplicates:
What does ‘: number’ after a struct field mean?
What does ‘unsigned temp:3’ means
I hate to ask this type of question, but it's really bugging me, so I will ask:
我讨厌问这种类型的问题,但它真的困扰着我,所以我会问:
What is the function of the : operator in the code below?
下面代码中 : 运算符的功能是什么?
#include <stdio.h>
struct microFields
{
unsigned int addr:9;
unsigned int cond:2;
unsigned int wr:1;
unsigned int rd:1;
unsigned int mar:1;
unsigned int alu:3;
unsigned int b:5;
unsigned int a:5;
unsigned int c:5;
};
union micro
{
unsigned int microCode;
microFields code;
};
int main(int argc, char* argv[])
{
micro test;
return 0;
}
If anyone cares at all, I pulled this code from the link below: http://www.cplusplus.com/forum/beginner/15843/
如果有人在乎,我从下面的链接中提取了此代码:http: //www.cplusplus.com/forum/beginner/15843/
I would really like to know because I know I have seen this before somewhere, and I want to understand it for when I see it again.
我真的很想知道,因为我知道我以前在某处见过这个,我想在我再次看到它时理解它。
回答by paxdiablo
They're bit-fields, an example being that unsigned int addr:9;creates an addrfield 9 bits long.
它们是位字段,一个例子是unsigned int addr:9;创建一个addr9 位长的字段。
It's commonly used to pack lots of values into an integral type. In your particular case, it defining the structure of a 32-bit microcode instruction for a (possibly) hypothetical CPU (if you add up all the bit-field lengths, they sum to 32).
它通常用于将大量值打包成一个整数类型。在您的特定情况下,它为(可能)假设的 CPU 定义了 32 位微码指令的结构(如果将所有位字段长度加起来,它们总和为 32)。
The union allows you to load in a single 32-bit value and then access the individual fields with code like (minor problems fixed as well, specifically the declarations of codeand test):
联合允许您加载单个 32 位值,然后使用如下代码访问各个字段(也修复了小问题,特别是code和的声明test):
#include <stdio.h>
struct microFields {
unsigned int addr:9;
unsigned int cond:2;
unsigned int wr:1;
unsigned int rd:1;
unsigned int mar:1;
unsigned int alu:3;
unsigned int b:5;
unsigned int a:5;
unsigned int c:5;
};
union micro {
unsigned int microCode;
struct microFields code;
};
int main (void) {
int myAlu;
union micro test;
test.microCode = 0x0001c000;
myAlu = test.code.alu;
printf("%d\n",myAlu);
return 0;
}
This prints out 7, which is the three bits making up the alubit-field.
这将打印出 7,这是组成alu位域的三位。
回答by dan04
回答by tgiphil
That's a declarator that specifies the number of bits for the variable.
这是一个声明符,用于指定变量的位数。
For more information see:
有关更多信息,请参阅:
http://msdn.microsoft.com/en-us/library/yszfawxh(VS.80).aspx
http://msdn.microsoft.com/en-us/library/yszfawxh(VS.80).aspx

