Bitwise Operators in C
Bitwise Operators in C
a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 250
b<<1 = 18
b>>1 = 4
1) The left shift and right shift operators should not be used for negative
numbers The result of << and >> is undefined behabiour if any of the operands is a negative
number. For example results of both -1 << 1 and 1 << -1 is undefined. Also, if the number is
shifted more than the size of integer, the behaviour is undefined. For example, 1 << 33 is
undefined if integers are stored using 32 bits.
2) The bitwise XOR operator is the most useful operator from technical interview
perspective.It is used in many problems. A simple example could be “Given a set of numbers where all
elements occur even number of times except one number, find the odd occuring number” This problem
can be efficiently solved by just doing XOR of all numbers.
// Function to return the only odd occurring element
int findOdd(int arr[], int n) {
int res = 0, i;
for (i = 0; i < n; i++)
res ^= arr[i];
return res;
}
int main(void) {
int arr[] = {12, 12, 14, 90, 14, 14, 14};
int n = sizeof(arr)/sizeof(arr[0]);
printf ("The odd occurring element is %d ", findOdd(arr, n));
return 0;
}
// Output: The odd occurring element is 90
int main()
{
int x = 2, y = 5;
(x & y)? printf("True ") : printf("False ");
(x && y)? printf("True ") : printf("False ");
return 0;
}
// Output: False True
4) The left-shift and right-shift operators are equivalent to multiplication and division
by 2 respectively.