Write four small functions to set, clear, toggle and test bit k of an unsigned value, and try them on 42.
#include <stdio.h>
unsigned set_bit(unsigned x, int k) { return x | (1u << k); }
unsigned clear_bit(unsigned x, int k) { return x & ~(1u << k); }
unsigned toggle_bit(unsigned x, int k) { return x ^ (1u << k); }
int test_bit(unsigned x, int k) { return (int) ((x >> k) & 1u); }
int main(void) {
unsigned x = 42; /* 101010 */
printf("x = %u, bit 3 is %d\n", x, test_bit(x, 3));
printf("set bit 0: %u\n", set_bit(x, 0));
printf("clear bit 5: %u\n", clear_bit(x, 5));
printf("toggle bit 2: %u\n", toggle_bit(x, 2));
return 0;
}
x = 42, bit 3 is 1 set bit 0: 43 clear bit 5: 10 toggle bit 2: 46
42 is 101010. Setting bit 0 adds 1 (43), clearing bit 5 removes 32 (10), and toggling bit 2 adds 4 because it was 0 (46). Returning new values instead of changing x makes each function easy to test.