How to set all odd position bits of a number

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{
static int generateMask(int n){
int count = 0;
int mask = 0;
int temp = n;
while(temp > 0){
if((count & 1) != 1)
mask = mask | (1 << count);
count++;
temp >>=1;
}
return mask;
}
static int setOddBits(int n) {
int mask = generateMask(n);
return (n | mask);
}
public static void main(String[] args) {
int n = 10;
System.out.println("Setting odd positioned bits of " + n + " we get " + setOddBits(n));
}
}

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.

Free Resources