/* CSE 303, Spring 2009, Marty Stepp This program has various functions related to getting/setting bits. */ #include #include int get_bit(int n, int b); void print_binary(int n); int set_bit(int n, int b, int value); // 119 => 1110111 // get_bit(119, 3) // (119 >> 3) => 1110 // (119 >> 3) & 1 => 0 // Returns the value of the b'th least significant bit of integer n. // pre: 0 <= b <= 31 int get_bit(int n, int b) { return ((n >> b) & 1); } // turn on bit #b // n = 119 => 1110111 // set_bit(n, b=3) ==> 127 // n | b // (119 | 2^3) // Sets the b'th least significant bit of integer n to the given value. // pre: 0 <= b <= 31, and 0 <= value <= 1 int set_bit(int n, int b, int value) { int bit = 1 << b; // b=3 --> bit= 1000 (8) if (value == 1) { // turn on bit b return n | bit; } else { // turn off bit b // bit2 = 11111111111111111111111110111 // n & bit2 return n & ~bit; } } // 42 --> 00000000000000000000000000101010 // ^ // ^ // ^ // Prints the given integer in binary. void print_binary(int n) { int i; bool seen1 = false; for (i = 31; i >= 0; i--) { if (get_bit(n, i) == 0) { if (seen1) { printf("0"); } } else { seen1 = true; printf("1"); } } printf("\n"); } int main(void) { int x1 = 42; // 101010 print_binary(x1); x1 = set_bit(x1, 0, 1); print_binary(x1); printf("%d\n", x1); x1 = set_bit(x1, 4, 1); print_binary(x1); printf("%d\n", x1); x1 = set_bit(x1, 13, 1); print_binary(x1); printf("%d\n", x1); x1 = set_bit(x1, 5, 0); print_binary(x1); printf("%d\n", x1); return 0; }