Related Tags

bitwise

# How to set all odd position bits of a number

Ravi

## Problem statement

Given a number n, set all the odd positioned bits of n. The position of LSB is considered to be 1.

Example 1:

• Input: n=8
• Output: 13

Example 2:

• Input: n=7
• Output: 7

### Solution

We’ll generate a bit mask that has all the odd positioned bits set and use the bitwise OR operation.

How do we generate a bit mask?

First, we’ll make a copy of n and call it temp. Two more variables are created as follows:

• count: This is used to generate the power of 2, which is used to create the mask.
• mask: This stores the bit mask.

The steps of the bit mask generation are as follows:

• Loop until the value of temp is greater than zero.
1. If the count is even, then we set the count-th bit in the mask.
2. We increment the count by 1.
3. We right shift the temp by 1.

### Code

Let's look at a code example.

class Main{

int count = 0;

int temp = n;
while(temp > 0){
if((count & 1) != 1)
count++;
temp >>=1;
}

}

static int setOddBits(int n) {
}

public static void main(String[] args) {
int n = 10;
System.out.println("Setting odd positioned bits of " + n + " we get " + setOddBits(n));
}
}
Try it out!

### Explanation

• Lines 3–16: We define the generateMask() method to implement the solution above to generate the bit mask.
• Lines 18–21: We define the setOddBits() method to set the odd positioned bits of a number by performing the bitwise OR of the given number, as well as the mask that we generate by calling generateMask().
• Line 24: We define n.
• Line 25: We call the generateMask() method with n as the parameter.

RELATED TAGS

bitwise

CONTRIBUTOR

Ravi
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 