Long.numberOfTrailingZeros()的Java实现 [英] Java implementation of Long.numberOfTrailingZeros()

查看:171
本文介绍了Long.numberOfTrailingZeros()的Java实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档链接: http://download.oracle.com/javase/6/docs/api/java/lang/Long.html#numberOfTrailingZeros%28long%29

以下是Java实现的源代码:

Here is the Java implementation source code:

/**
 * Returns the number of zero bits following the lowest-order ("rightmost")
 * one-bit in the two's complement binary representation of the specified
 * <tt>long</tt> value.  Returns 64 if the specified value has no
 * one-bits in its two's complement representation, in other words if it is
 * equal to zero.
 *
 * @return the number of zero bits following the lowest-order ("rightmost")
 *     one-bit in the two's complement binary representation of the
 *     specified <tt>long</tt> value, or 64 if the value is equal
 *     to zero.
 * @since 1.5
 */
public static int numberOfTrailingZeros(long i) {
    // HD, Figure 5-14
int x, y;
if (i == 0) return 64;
int n = 63;
y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
y = x <<16; if (y != 0) { n = n -16; x = y; }
y = x << 8; if (y != 0) { n = n - 8; x = y; }
y = x << 4; if (y != 0) { n = n - 4; x = y; }
y = x << 2; if (y != 0) { n = n - 2; x = y; }
return n - ((x << 1) >>> 31);
}

此算法很长时间分成两个int并与每个int进行交易。我的问题是为什么不使用y = x<

This algorithm breaks long into two ints and deals with each int. My question is why not use y = x << 32 instead of breaking the long apart?

这里是我的版本:

public static int bit(long i)
{
    if (i == 0) return 64;
    long x = i;
    long y;
    int n = 63;
    y = x << 32; if (y != 0) { n -= 32; x = y; }
    y = x << 16; if (y != 0) { n -= 16; x = y; }
    y = x <<  8; if (y != 0) { n -=  8; x = y; }
    y = x <<  4; if (y != 0) { n -=  4; x = y; }
    y = x <<  2; if (y != 0) { n -=  2; x = y; }
    return (int) (n - ((x << 1) >>> 63));
}

我测试了这两种方法并取平均值。实施时间:595,我的版本时间:593。也许最初的实施在32位系统上更快,因为我使用的是Windows 7 64位。至少Java应该在x64 sdk中使用类似我的版本的东西。有什么想法吗?

I tested both methods and averaged. Implementation time: 595, my version time: 593. Maybe the original implementation is faster on 32-bit systems, because I'm using Windows 7 64-bit. At least Java should use something like my version in their x64 sdk. Any ideas?

推荐答案

几乎在每个应用程序中,都可以忽略0.5%的性能差异。如果您在一个需要窥视性能的应用程序上工作,则可以自己实现。

A performance difference of 0.5 percent can be ignored in almost every application. If you work on the one application that needs peek performance for this single method you can implement it yourself.

这篇关于Long.numberOfTrailingZeros()的Java实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆