/* shift.c * Demonstrates the different effects of setting bits * in combination with signed and unsigned "8-bit" data. */ #include #include void print_binary(unsigned char number, int size) { if (size == 0) { return; } if (size == 1) { putc((number & 1) ? '1' : '0', stdout); return; } print_binary(number >> 1, size - 1); putc((number & 1) ? '1' : '0', stdout); } // Function to set the kth bit of n int setBit(int n, int k) { return (n | (1 << k)); } // Function to clear the kth bit of n int clearBit(int n, int k) { return (n & (~(1 << k))); } // Function to toggle the kth bit of n int toggleBit(int n, int k) { return (n ^ (1 << k)); } // Driver code int main(int argc, char **argv) { unsigned char n = 0xaa; int k = 0; if (argc != 3) { printf("Usage: ./bitop (between 01 and 0xFF in hex) (between 0 and 7) \n"); printf(" Kth bit to be manipulated\n"); return 1; } n = (int)strtol(argv[1], NULL, 16); k = atoi(argv[2]); printf("Number :"); print_binary(n, 8); printf("\n Set %d-th: ", k); print_binary(setBit(n, k), 8); printf("\n"); printf("Number :"); print_binary(n, 8); printf("\n Clear %d-th: ", k); print_binary(clearBit(n, k), 8); printf("\n"); printf("Number :"); print_binary(n, 8); printf("\n Toggle %d-th: ", k); print_binary(toggleBit(n, k), 8); printf("\n"); }