Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

bitwise

How to set all the even positioned bits of a number

Ravi

Problem statement

Given a number n, set all the even positioned bits of n.

Example 1

  • Input: n=10
  • Output: 10

Example 2

  • Input: n=8
  • Output: 10

Solution

The steps in the algorithm are as follows:

  1. Generate a bit mask where the even positioned bits are set.
  2. Perform a bitwise OR operation and mask the given number.

How to generate the bit mask

The steps to generate the bit mask are as follows:

  1. We have two variables, such as count and mask.
  2. We use a temporary variable temp in a for loop, and perform the following steps until temp becomes zero. The temp is right-shifted until it becomes zero.
    1. If the count is odd, we then left shift count by 1 and perform bitwise OR with the mask.
    2. Then, we increment the count by 1.

Code

class Main{

    static int generateMask(int n){
        int count = 0, mask = 0;
        for (int temp = n; temp > 0; temp >>= 1) {
            if ((count & 1) > 0) mask |= (1 << count);
            count++;
        }
        return mask;
    }

    static int setEvenPositionedBits(int n) {
        int mask = generateMask(n);
        return (n | mask);
    }

    public static void main(String[] args) {
        int n = 8;
        System.out.println("Setting even positioned bits of " + n + " we get " + setEvenPositionedBits(n));
    }
}

Explanation

  • Lines 3–10: We define the generateMask() method, where n, the even positioned set bit mask, is generated.
  • Lines 12–15: We define the setEvenPositionedBits() method where all even positioned bits of n are set.
  • Line 18: We define n.
  • Line 19: The setEvenPositionedBits() method is invoked with n as the argument.

RELATED TAGS

bitwise
RELATED COURSES

View all Courses

Keep Exploring