/* This example illustrates a couple of ways in which we can make use of bit manipulation operators. To compile: gcc -o 09-bits 09-bits.c -Wall To run: ./09-bits C. Andrews 2016-03-04 */ #include // #define is a way to _define_ values (or macros) that can be used in your code // It is the recommended way to create constants // here we are making bitmasks that represent different boolean states #define LIKES_DW 1 // first bit #define LIKES_BLACK 2 // second bit int main(int argc, char * argv[]){ short x = 593; // this illustrates using bit shifting and masking (ANDing to a value with 1s in the position we are interested in) to extract individual bytes out of a number printf("%#x : %#x %#x\n",x, (x >> 8) & 0xff, x & 0xff); // we extend this idea to loop through all of the bits of a number to see the binary representation // We start at the highest order bit // since this is a short, we have 16 bits, so we want to start by shifting over by 15 to get at that one bit for (int i = sizeof(x)*8-1; i >= 0; i--){ // here is the shift and the mask printf("%d", (x >> i)& 1); // to make this a little easier to compare to our hex, we insert spaces every four digits if (i % 4 == 0){ printf(" "); } } printf("\n"); // example of creating a variable to hold a collection of boolean flags char flags = 0; // we can set the flags using the bitwise OR flags = LIKES_DW | LIKES_BLACK; // we can query the collection of flags by masking against the original value if (flags & LIKES_BLACK){ printf("likes black\n"); } return 0 ; }