Just to clarify this is NOT a matter of homework, as I have seen that such accusations spilled out in contrast to other beat-hacking issues:
However, I have a bit in C:
#include <stdio.h>
const int __FLOAT_WORD_ORDER = 0;
const int __LITTLE_END = 0;
int log2hack(int v)
{
union { unsigned int u[2]; double d; } t;
t.u[0]=0;
t.u[1]=0;
t.d=0.0;
t.u[__FLOAT_WORD_ORDER==__LITTLE_END] = 0x43300000;
t.u[__FLOAT_WORD_ORDER!=__LITTLE_END] = v;
t.d -= 4503599627370496.0;
return (t.u[__FLOAT_WORD_ORDER==__LITTLE_END] >> 20) - 0x3FF;
}
int main ()
{
int i = 25;
int j = 33;
printf("Log2n(25)=%i!\n",
log2hack(25));
printf("Log2n(33)=%i!\n",
log2hack(33));
return 0;
}
I want to convert this to Java. So far I have:
public int log2Hack(int n)
{
int r;
int[] u = new int [2];
double d = 0.0;
if (BitonicSorterForArbitraryN.__FLOAT_WORD_ORDER==
BitonicSorterForArbitraryN.LITTLE_ENDIAN)
{
u[1] = 0x43300000;
u[0] = n;
}
else
{
u[0] = 0x43300000;
u[1] = n;
}
d -= 4503599627370496.0;
if (BitonicSorterForArbitraryN.__FLOAT_WORD_ORDER==
BitonicSorterForArbitraryN.LITTLE_ENDIAN)
r = (u[1] >> 20) - 0x3FF;
else
r = (u[0] >> 20) - 0x3FF;
return r;
}
(Note that this is inside the bit sort class ...)
Anyway, when I run it for the same values of 33 and 25, I get 52 in each case.
I know Java integers are signed, so I'm sure it has something to do with why this happens. Does anyone have any ideas how I can get this 5-op, 32-bit integer log 2 to work in Java?
P.S. , :
http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogIEEE64Float