// CS 350, Illinois Inst Tech, J. Sasaki // Lecture 8, Spring 2012 // // Bit selection examples in C // #include int main(void) { int x = 0x12345678, y = 0xcdef0123; // For printing: // %x -- print in hex (as many characters as necessary) // %08x -- print zero-filled, >= 8 characters, in hex // printf("%x & %x = %08x (bitwise and)\n", x, y, x & y); printf("%x | %x = %08x (bitwise or)\n", x, y, x | y); printf("%x ^ %x = %08x (bitwise xor)\n", x, y, x ^ y); printf("\n"); printf("%x && %x = %d (logical and)\n", x, y, x && y); printf("%x || %x = %d (logical or)\n", x, y, x || y); printf("\n"); printf("!! %x = %d, !! %x = %d\n", x, !!x, y, !!y); printf("\n"); printf(" %x != %x = %d (inequality)\n", x, y, x != y); printf("!! %x != !! %x = %d (logical xor)\n", x, y, !!x != !!y); printf("\n"); // Using xor's properties of associativity, commutativity, and N ^ N = 0, // we can swap two variables without using a temporary location. // // Note: x ^= y means x = x ^ y. (Also exist &= and |= operators) // printf("x = %x, y = %x\n", x, y); // Say x = A and y = B x ^= y; // Now x = A^B, y = B y ^= x; // x = A^B, y = B^(A^B) = (B^B)^A = 0^A = A x ^= y; // x = (A^B)^A = (A^A)^B = B, y = A printf("x = %x, y = %x after x ^= y; y ^= x; x ^= y\n", x, y); printf("\n"); int bitnbr = 2; int mask = 1 << bitnbr; // << is left shift, >> is right shift int value = 0x01234563; printf("%08x | %08x = %08x (set bit %d)\n", value, mask, value | mask, bitnbr); value = 0x01234567; printf("%08x & %08x = %08x (select bit %d)\n", value, mask, value & mask, bitnbr); value = 0xffffffff; printf("%08x ^ %08x = %08x (reverse mask %d)\n", value, mask, value ^ mask, bitnbr); int reverse_mask = 0xffffffff ^ mask; value = 0x0123cdef; printf("%08x & %08x = %08x (unset bit %d)\n", value, reverse_mask, value & reverse_mask, bitnbr); return 0; }