Trusted answers to developer questions

Ravi

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.

- Input: 18
- Output: 2

The binary representation of 18 is `10010`

. So, the even-positioned bits are **1**0**0**1**0**. When we turn off all the even positioned bits, we get `00010`

, that is, `2`

.

- Input: 15
- Output: 10

The binary representation of 15 is `1111`

. So, the even-positioned bits are 1**1**1**1**. 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)); } }

Unset all even-positioned bits

- 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

Related Courses