0

Recently I stumbled upon a code written like this:

typedef struct
{
  uint8_t TC0_WG0     :2;
  uint8_t TC0_CS      :3;
} Timer0;

What I wanted to know is what does the part that says :2; & :3; specifically mean? Is it accessing the bits 0, 1, 2 only or 0, 1, 2 & 3 only of the 8-bit unsigned character or what ?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Mahmoud Ayman
  • 197
  • 1
  • 13

2 Answers2

1

These are basically bitfields explicitly telling that the TC0_CS would be in 3 bit.

These can be used to save space. In embedded system, I have faced this use when designing an interrupt system. Used bitfield to specify the specific positions as a way to activate deactivate interrupts.

He is not accessing the 0,1 or 2nd bits but OP can using appropriate bit masking.

user2736738
  • 30,591
  • 5
  • 42
  • 56
1

It is called bit-field members.

cppreference say's :

Bit fields

Declares a member with explicit width, in bits. Adjacent bit field members may be packed to share and straddle the individual bytes.

A bit field declaration is a struct or union member declaration which uses the following declarator:

identifier(optional) : width      

identifier - the name of the bit field that is being declared. The name is optional: nameless bitfields introduce the specified number of bits of padding

width - an integer constant expression with a value greater or equal to zero and less or equal the number of bits in the underlying type. When greater than zero, this is the number of bits that this bit field will occupy. The value zero is only allowed for nameless bitfields and has special meaning: it specifies that the next bit field in the class definition will begin at an allocation unit's boundary.

msc
  • 33,420
  • 29
  • 119
  • 214