1. Detect if two integers have opposite signs.
/* Using XOR operator * Examples: isOppositeSigns(4, -5) = true; * isOppositeSigns(4, 5) = false; */ boolean isOppositeSigns(int x, int y) { return ((x ^ y) < 0); }
2. Determining if an integer is a power of 2.
/* Note that 0 is incorrectly considered a power of 2 * Examples: isPowerOfTwo(4) = true; isPowerOfTwo(3) = false; */ boolean isPowerOfTwo(int v) { return (v & (v -1 )) == 0; }
3. Swap the values of a and b without using a temporary variable.
// Swapping values with XOR int a = 10, b = 9; a ^= b; b ^= a; a ^= b;
4. Check non-zero.
/* * isNonZero - Check whether x is nonzero * Examples: isNonZero(3) = 1, isNonZero(0) = 0 */ int isNonZero(int x) { /* 0 is special since negating it returns same number * (and thus both have 0 sign bit). * Shift sign bits, OR them, and mask against 1 to see * if either had a 1 sing bit */ int n = ~x + 1; return ((n >> 31) | (x >> 31)) & 1; }
References:
- Gayle Laakmann Mcdowell, “Bit Manipulation”, in Cracking the code interview, 6th Edition.
- Bit Twiddling Hacks, Accessed at https://graphics.stanford.edu/~seander/bithacks.html
- Bit Manipulation Tricks, Accessed at http://bits.stephan-brumme.com/
- Summary of Operators. Accessed at https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
- Bit Math (VN),http://arduino.vn/reference/bit-math-cac-phep-toan-thao-tac-tren-bit