Data Structures | Array | Question 2
Which of the following operations can be performed using bitwise operators in C to check if a number is a power of 2?
(A)
AND
(B)
OR
(C)
XOR
(D)
Shift
Answer: (A)
Explanation:
To check if a number is a power of 2 using bitwise operators in C, we can perform a bitwise AND operation between the given number and its one less value. If the result of this operation is zero, then the number is a power of 2.
For example, let’s say we want to check if the number x is a power of 2. We can do this as follows:
C++
if ((x & (x-1)) == 0) { // x is a power of 2 } else { // x is not a power of 2 } |
Here, the & operator performs a bitwise AND operation, and the (x-1) term flips all the bits after the rightmost set bit in x. If x is already a power of 2, then x-1 will have all the bits flipped except for the rightmost set bit, which will remain unchanged. Therefore, the bitwise AND operation will yield zero. On the other hand, if x is not a power of 2, then x-1 will have at least two set bits that are adjacent, and the bitwise AND operation will yield a non-zero value.
Quiz of this Question
Please comment below if you find anything wrong in the above post
Please Login to comment...