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 colon1struct Flags { // 1 bit, so active can only be 0 or 12 unsigned int active : 1; // Another 1-bit flag3 unsigned int ready : 1; // A third 1-bit flag4 unsigned int error : 1; // 4 bits hold values from 0 to 155 unsigned int mode : 4;6};7 // Initializes the fields in declaration order: active 1, ready 0, error 1, mode 58struct Flags f = {1, 0, 1, 5};// Bit fields are read like normal members: prints active: 19printf("active: %u\n", f.active);// Prints ready: 010printf("ready: %u\n", f.ready);// Prints error: 111printf("error: %u\n", f.error);// Prints mode: 512printf("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. 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