Construct a number using alternate bits from two integers. We create a number using the first bit of the second number, the second bit of the first number, the third bit of a second number, the fourth bit of a first number, and so on.
Looking at the pattern mentioned above:
x
.y
.OR
of the result from steps 1 and 2.The reference to obtain the odd/even positions of bits are as follows:
- Refer How to set all even position bits of a number? for step 1.
- Refer How to set all odd position bits of a number? for step 2.
Let’s look at the code below:
class Main{static int setEvenPositionBits(int x) {int temp = x;int count = 0;int res = 0;for (temp = x; temp > 0; temp >>= 1) {if (count % 2 == 1)res |= (1 << count);count++;}return (x & res);}static int setOddPositionBits(int y) {int count = 0;int res = 0;for (int temp = y; temp > 0; temp >>= 1) {if (count % 2 == 0)res |= (1 << count);count++;}return (y & res);}static int getAlternateBits(int x, int y) {int tempX = setEvenPositionBits(x);int tempY = setOddPositionBits(y);return tempX | tempY;}public static void main(String[] args) {int x = 34;int y = 43;System.out.println(getAlternateBits(x, y));}}
getAlternateBits()
method that invokes setOddPositionBits()
and setEvenPositionBits()
methods and performs a bitwise OR
operation on the return values of the methods.x
is defined.y
is defined.getAlternateBits()
method.