Java 有可能在双精度存储器中获得原始位吗?
我只是想把我用C/C++编写的以下方法转换成Java。简而言之,该代码提供了一种非常有效的方法来计算设置为1的数字的最左边和最右边位的索引。这两种方法基于Knuth的《计算机编程艺术》第4卷中的代码Java 有可能在双精度存储器中获得原始位吗?,java,Java,我只是想把我用C/C++编写的以下方法转换成Java。简而言之,该代码提供了一种非常有效的方法来计算设置为1的数字的最左边和最右边位的索引。这两种方法基于Knuth的《计算机编程艺术》第4卷中的代码 // Returns index of the left-most bit of x that is one in the binary // expansion of x. Assumes x > 0 since otherwise lambda(x) is undefined. // Ca
// Returns index of the left-most bit of x that is one in the binary
// expansion of x. Assumes x > 0 since otherwise lambda(x) is undefined.
// Can be used to calculate floor(log(x, 2)), the number of binary digits
// of x, minus one.
int lambda(unsigned long x) {
double y = (double) x;
// Excuse the monstrocity below. I need to have a long that has the raw
// bits of x in data. Simply (long)y would yield x back since C would cast
// the double to a long. So we need to cast it to a (void *) so that C
// "forgets" what kind of data we are dealing with, and then cast it to
// long.
unsigned long xx = *((long *)((void*)&y));
// The first 52 bits are the the significant. The rest are the sign and
// exponent. Since the number is assumed to be positive, we don't have to
// worry about the sign bit being 1 and can simply extract the exponent by
// shifting right 52 bits. The exponent is in "excess-1023" format so we
// must subtract 1023 after.
return (int)(xx >> 52) - 1023;
}
// Returns the index of the right-most one bit in the binary expansion of x
int rho(unsigned long x) {
return lambda(x & -x);
}
正如您所看到的,我需要一个具有相同位的double的long,但是没有
void*
cast,我不知道如何在Java中实现这一点。有什么想法吗?甚至有可能吗?有一个静态函数来执行类型转换
long xx = Double.doubleToLongBits(y);
return (int) (xx >>> 52) - 1023;
注意,右移时,>
将long视为无符号值
然而,阅读评论,听起来你想要的是一个简单的函数
我想这在大多数当前的体系结构上更有效,但您必须对其进行分析才能确定。有一种类似的“尾随零”方法来计算
rho()
函数。请注意,您开始使用的“C/C++”代码不起作用:它破坏了严格的别名规则,即使中间转换为void*
。只有大多数编译器生成的代码符合程序员的意图。在C中,memcpy()
或联合是访问表示的合适方法。
return 63 - Long.numberOfLeadingZeros(x);