Given a number n
, unset all bits at even positions. The indexing is zero-based indexing where the rightmost bit/least significant bit is 0-th
index.
Consider that the maximum number can be 32-bit.
The binary representation of 18 is 10010
. So, the even-positioned bits are 10010. When we turn off all the even positioned bits, we get 00010
, that is, 2
.
The binary representation of 15 is 1111
. So, the even-positioned bits are 1111. When we turn off all the even positioned bits, we get 1010
, that is, 10
.
The solution is to generate a mask where the even positioned bits are zero and the odd positioned bits are ones. Since the maximum number of bits is 32, the bits mask is as follows:
10101010101010101010101010101010
In the mask above, all the even positioned (zero-based indexing is followed) bits are unset and all the odd positioned bits are set.
The above bits representation in hexadecimal is 0xaaaaaaaa
.
Now, if we take a bitwise AND between the input number, the mask unsets the bits at even positions.
Let’s look at the code below:
class Main{ static int unSetEvenPositionedBits(int n) { return (n & 0xaaaaaaaa); } public static void main(String[] args) { int n = 15; System.out.println("Unsetting even positioned bits of " + n + " we get " + unSetEvenPositionedBits(n)); n = 18; System.out.println("Unsetting even positioned bits of " + n + " we get " + unSetEvenPositionedBits(n)); n = 100; System.out.println("Unsetting even positioned bits of " + n + " we get " + unSetEvenPositionedBits(n)); } }
unSetEvenPositionedBits()
method that takes an input number n
and unsets all even positioned bits in that number.n
with 15
as the value.unSetEvenPositionedBits()
for the value 15
and print result to the console.n
and print results to the console.RELATED TAGS
CONTRIBUTOR
View all Courses