Bit Field Structure in C

Level 5313 keystrokes

Declares a struct with bit fields, three 1-bit flags and a 4-bit mode, initializes it with {1, 0, 1, 5} and prints each field. The 7 bits fit in one unsigned int, so sizeof reports 4 bytes on typical systems.

C code

// Each member declares how many bits it uses after the colon
1struct Flags {
// 1 bit, so active can only be 0 or 1
2 unsigned int active : 1;
// Another 1-bit flag
3 unsigned int ready : 1;
// A third 1-bit flag
4 unsigned int error : 1;
// 4 bits hold values from 0 to 15
5 unsigned int mode : 4;
6};
7
// Initializes the fields in declaration order: active 1, ready 0, error 1, mode 5
8struct Flags f = {1, 0, 1, 5};
// Bit fields are read like normal members: prints active: 1
9printf("active: %u\n", f.active);
// Prints ready: 0
10printf("ready: %u\n", f.ready);
// Prints error: 1
11printf("error: %u\n", f.error);
// Prints mode: 5
12printf("mode: %u\n", f.mode);
// The 7 bits fit in one unsigned int, typically 4 bytes (the layout is implementation-defined)
13printf("Size: %lu bytes\n", sizeof(f));

Output

active: 1
ready: 0
error: 1
mode: 5
Size: 4 bytes
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 11
  • "× 10
  • :× 9
  • ,× 8
  • (× 6
  • )× 6
  • \× 5
  • %× 5
  • .× 4
  • {× 2

More C examples at level 5

← C typing practice