c - 使用 : operator in C

标签 c syntax

<分区>

Possible Duplicates:
What does ‘: number’ after a struct field mean?
What does ‘unsigned temp:3’ means

我讨厌问这种类型的问题,但它真的很烦我,所以我会问:

下面代码中的 : 运算符的作用是什么?

#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;
} 

如果有人关心,我从下面的链接中提取了这段代码: http://www.cplusplus.com/forum/beginner/15843/

我真的很想知道,因为我知道我以前在某个地方见过这个,我想在我再次看到它时理解它。

最佳答案

它们是位字段,例如 unsigned int addr:9; 创建一个 9 位长的 addr 字段。

它通常用于将大量值打包成一个整数类型。在您的特定情况下,它为(可能)假设的 CPU 定义了 32 位微代码指令的结构(如果您将所有位字段长度加起来,它们的总和为 32)。

union 允许您加载单个 32 位值,然后使用类似代码访问各个字段(也修复了一些小问题,特别是 codetest< 的声明):

#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;
}

这会打印出 7,这是构成 alu 位域的三位。

关于c - 使用 : operator in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3305933/

相关文章:

java - 找不到 jni.h

c - 如何在 C 中将 ENUM 作为函数参数传递

c++ - C/C++ 与 Python 之间交换值的应用程序设计

python - != 和 <> 有什么区别?

c++ - 一维数组衰减为指针,但二维数组不会衰减,为什么?

c - 如何知道我的参数是 char 还是带有 varargs 的 char*

c++ - 为什么这个 C++ 函数定义不需要花括号?

PowerShell $_ 语法

c - 嵌套 IF-ELSE 之前的 IF 语句

performance - begin-end block 是否会影响条件语句的性能?