Given a number n
, set all the even positioned bits of n
.
n=10
10
n=8
10
The steps in the algorithm are as follows:
OR
operation and mask the given number.The steps to generate the bit mask are as follows:
count
and mask
.temp
in a for
loop, and perform the following steps until temp
becomes zero. The temp
is right-shifted until it becomes zero.
count
by 1 and perform bitwise OR
with the mask
.count
by 1.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));}}
generateMask()
method, where n
, the even positioned set bit mask, is generated.setEvenPositionedBits()
method where all even positioned bits of n
are set.n
.setEvenPositionedBits()
method is invoked with n
as the argument.