/* File: bitop.c bitop.c is an equivalent C program for the Ch program bitop.ch without using the printing format "%b" and binary constant 0bxxxx. Apply bitwise operators to variables with 1 byte */ #include /* function printbits() prints each bit of the passed argument 'c' */ int printbits(char c) { int mask, /* declare mask */ num, /* num of bits for the passed variable */ i, /* index variable for the for-loop */ bit; /* the binary value 1 or 0 for a bit */ num = sizeof(char)*8;/* number of bits for a char, 8 bits for a byte */ /* Assume bit positions are [8 7 6 5 4 3 2 1]. Obtain the binary value 1 or 0 at each position, starting with the most left bit */ for(i=num; i>=1 ; i--) { mask = 1 << (i-1); /* (i)th bit of mask is 1 /* (i)th bit of (c & mask) is 1 only if (i)th bit of c is 1, (c & mask) != 0 is 1; Otherwise, it is 0. */ bit = (c & mask) != 0; printf("%d", bit); /* print either 1 or 0 for the value of bit */ } printf("\n"); return 0; } int main() { /* declare variables and initialize with hexadecimal numbers */ char a = 0xB4; /* 0xB4 is 0b10110100 */ char b = 0xD9, c; /* 0xD9 is 0b11011001 */ /* apply bitwise operators to variables a and b */ printf("a = 0b"); printbits(a); printf("b = 0b"); printbits(b); c = a & b; printf("a & b = 0b"); printbits(c); c = a | b; printf("a | b = 0b"); printbits(c); c = a ^ b; printf("a ^ b = 0b"); printbits(c); c = b << 1; printf("a <> 1; printf("a >>b = 0b"); printbits(c); c = ~a; printf("~a = 0b"); printbits(c); return 0; }