Bit Field - Examples

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; }

Read more about this topic:  Bit Field

Famous quotes containing the word examples:

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)

    No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.
    André Breton (1896–1966)

    In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.
    Michel de Montaigne (1533–1592)