So I was given the task of interleaving two 32-bit integer into one, like this:
a_31,...,a_0 and b_31,...,b_0, return the 64-bit long that contains their bits interleaved: a_31,b_31,a_30,b_30,...,a_0,b_0.
I tried doing it by taking the MSB from each with a helper who has 1 in the MSB place and then combining them.
basically putting the "a" int in the odd places and the "b" int bits in the even places.
I cannot call other function (even Math.pow)
My code:
public static long interleave(int a, int b) {
long tempA = a;
long tempB = b;
long helper = 0x0000000080000000L;
long ans=0;
for (int i = 0; i <32 ; i++) {
ans = ans | ((helper & tempA) << (31-(2*i)));
ans = ans | ((helper & tempB)<<(30-(i+i)));
helper = helper >>>1;
}
return ans;
}
my test failed here:
Expected :-6148914691236517206
Actual :7905747459547660288
some help with the debugging and figuring out the problem would be nice, as well as suggestions to how to fix the problem.