在64位整数寻找最高和最低显著位设置的快捷方法 [英] Fast way of finding most and least significant bit set in a 64-bit integer

查看:198
本文介绍了在64位整数寻找最高和最低显著位设置的快捷方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多关于这个StackOverflow上的问题。 许多。但是我无法找到一个答案是:

There are a lot of questions about this on StackOverflow. A lot. However I cannot find an answer that:


  • 作品在C#

  • 作品的64位整数(而不是32位)

更快比:

private static int Obvious(ulong v)
{
    int r = 0;
    while ((v >>= 1) != 0) 
    {
        r++;
    }
    return r;
}

甚至

int r = (int)(Math.Log(v,2));

我在这里假设一个64位的英特尔CPU。

I'm assuming a 64-bit Intel CPU here.

一个有用的参考是位黑客页面,另一个是<一个HREF =htt​​p://www.jjj.de/fxt/fxtbook.pdf相对=nofollow> fxtbook.pdf
然而,尽管这些给人有益的方向来解决这个问题,他们不给一个现成的答案。

One useful reference is the Bit Hacks page and another is fxtbook.pdf However, while these gives useful direction to approach the problem, they do not give a ready answer.

我可重复使用的功能,可以做同样的事情到 _BitScanForward64后很 _BitScanReverse64 只为C#。

I'm after a re-usable function that can do something similar to _BitScanForward64 and _BitScanReverse64 only for C#.

推荐答案

按我的意见,这是C#中的函数来计算领先修改为64位整数零位。

As per my comment, this is a function in C# to count leading zero bits modified for a 64 bit integer.

public static UInt64 CountLeadingZeros(UInt64 input)
{
    if (input == 0) return 64;

    UInt64 n = 1;

    if ((input >> 32) == 0) { n = n + 32; input = input << 32; }
    if ((input >> 48) == 0) { n = n + 16; input = input << 16; }
    if ((input >> 56) == 0) { n = n + 8; input = input << 8; }
    if ((input >> 60) == 0) { n = n + 4; input = input << 4; }
    if ((input >> 62) == 0) { n = n + 2; input = input << 2; }
    n = n - (input >> 63);

    return n;
}

这篇关于在64位整数寻找最高和最低显著位设置的快捷方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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