Use of the : operator in C [duplicate]

老子叫甜甜 提交于 2019-11-26 09:41:24

问题


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/

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.


回答1:


They're bit-fields, an example being that unsigned int addr:9; creates an addr field 9 bits long.

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).

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 code and 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 alu bit-field.




回答2:


It's a bit field. The number after the colon is how many bits each variable takes up.




回答3:


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



来源:https://stackoverflow.com/questions/3305933/use-of-the-operator-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!