How to set all the even positioned bits of a number
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:
- Generate a bit mask where the even positioned bits are set.
- Perform a bitwise
ORoperation and mask the given number.
How to generate the bit mask
The steps to generate the bit mask are as follows:
- We have two variables, such as
countandmask. - We use a temporary variable
tempin aforloop, and perform the following steps untiltempbecomes zero. Thetempis right-shifted until it becomes zero.- If the count is odd, we then left shift
countby 1 and perform bitwiseORwith themask. - Then, we increment the
countby 1.
- If the count is odd, we then left shift
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, wheren, the even positioned set bit mask, is generated. - Lines 12–15: We define the
setEvenPositionedBits()method where all even positioned bits ofnare set. - Line 18: We define
n. - Line 19: The
setEvenPositionedBits()method is invoked withnas the argument.