Related Tags

java

# How to unset all even positioned bits

Ravi

### Problem statement

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.

#### Example 1

• Input: 18
• Output: 2

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.

#### Example 2

• Input: 15
• Output: 10

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.

### Solution

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.

### Code example

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));
}
}
Unset all even-positioned bits

### Code explanation

• Lines 3 to 5: We define the unSetEvenPositionedBits() method that takes an input number n and unsets all even positioned bits in that number.
• Line 8: We initialize variable n with 15 as the value.
• Line 9: We call unSetEvenPositionedBits() for the value 15 and print result to the console.
• Lines 10 to 13: We overwrite values in the variable n and print results to the console.

RELATED TAGS

java

CONTRIBUTOR

Ravi
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 