简体   繁体   中英

Microchip bending the rules of C?

I was digging through some headder files relating to a PIC microcontroller when I came accross a load of structs that look like this:

typedef struct tagPORTDBITS {
  unsigned RD0:1;
  unsigned RD1:1;
  unsigned RD2:1;
  unsigned RD3:1;
  unsigned RD4:1;
  unsigned RD5:1;
  unsigned RD6:1;
  unsigned RD7:1;
  unsigned RD8:1;
  unsigned RD9:1;
  unsigned RD10:1;
  unsigned RD11:1;
  unsigned RD12:1;
  unsigned RD13:1;
  unsigned RD14:1;
  unsigned RD15:1;
} PORTDBITS;

Is this standard C? I cant find any other referances to anything that looks like this, ie with the ":1" after the variable definition

I assume all the elements are representing bits, so is this a Microchip addition to their C compiler to make things easier for embeded programmers?

This is a C bitfield , which is a perfectly valid (although unportable) construct. See here or here for more info.

Although the data layout in a bitfield is implementation-defined and therefore unportable, they are often used in embedded processing to map individual bits of a register to logical names. This works because most embedded processors use their own specific toolchain where the bitfield layout rules are well understood.

是的,这是标准C.这个名称是位字段

This is standard C. It is called a bit-field

This struct definition is commonly used for exactly what you provided as example: Making bitwise data communication more easy to read, because you can then access single bits easily with a name instead of shifting or bitwise operations and struggling around with bytes, while still having the ability to use the data directly as a single integer or byte.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM