For CS351, Intro to Systems, we had to do several operations using bit operators only. These took awhile, but are pretty cool to show off. We were graded by how few operations we used to return the right values for the generated test cases, including some difficult boundary ones.
1 2 3 4 | //NOR operation using only ~ and & int bitNor(int x, int y) { return (~x)&(~y); } |
The XOR operation is equivalent to the (x NAND y) AND (x OR y).
1 2 3 4 | //XOR operation using only ~ and & int bitXor(int x, int y) { return (~(x&y))&(~((~x)&(~y))); } |
1 2 3 4 | //Return true if x is not equal to y not using comparison operators. int isNotEqual(int x, int y) { return !!(x^y); } |
There are two types of shifts, arithmetic and logical. Left shifts are the same in both types, but right shifts are different. Logical shifts insert zeroes to fill in the empty spaces to keep the logic of the bits, but arithmetic shifts fill in the value of the sign bit to preserve the sign of the operand in twos-complement integers.
1 2 3 4 5 | int rightLogicalShift(int x, int n) { int allOnes = ~0; int y = ~((allOnes) << (32 + (~n + 1))); return ((x >> n) & y); } |