Examples
Declaring a bit field in C:
#include
// opaque and show
#define YES 1
#define NO 0
// line styles
#define SOLID 1
#define DOTTED 2
#define DASHED 3
// primary colors
#define BLUE 4 // 100
#define GREEN 2 // 010
#define RED 1 // 001
// mixed colors
#define BLACK 0 // 000
#define YELLOW (RED | GREEN) // 011
#define MAGENTA (RED | BLUE) // 101
#define CYAN (GREEN | BLUE) // 110
#define WHITE (RED | GREEN | BLUE) // 111
const char * colors = {"Black", "Red", "Green", "Yellow", "Blue", " Magenta", "Cyan", "White"};
// bit field box properties
struct box_props
{ unsigned int opaque : 1; unsigned int fill_color : 3; unsigned int : 4; // fill to 8 bits unsigned int show_border : 1; unsigned int border_color : 3; unsigned int border_style : 2; unsigned int : 2; // fill to 16 bits
};
Example of emulating bit fields with a primitive and bit operators in C:
/* Each prepocessor directive defines a single bit */
#define KEY_UP (1 << 0) // 000001
#define KEY_RIGHT (1 << 1) // 000010
#define KEY_DOWN (1 << 2) // 000100
#define KEY_LEFT (1 << 3) // 001000
#define KEY_BUTTON1 (1 << 4) // 010000
#define KEY_BUTTON2 (1 << 5) // 100000
int gameControllerStatus = 0;
/* Sets the gameCtrollerStatus using OR */
void keyPressed(int key) { gameControllerStatus |= key;
}
/* Turns the key in gameControllerStatus off using AND and ~ */
void keyReleased(int key) { gameControllerStatus &= ~key;
}
/* Tests whether a bit is set using AND */
int isPressed(int key) { return gameControllerStatus & key;
}