C#。在ulong中连续计数1位

时间:2016-04-21 11:42:52

标签: c#

基本上我想计算ulong中连续1位(1位组)的数量。例如: ulong x = 0x1BD11BDAA9FC1A22UL; 二进制变为:1101111010001000110111101101010101001111111000001101000100010。 我需要输出为No连续1位= 16。

5 个答案:

答案 0 :(得分:4)

转换为bitstring,在删除空条目时以0字符拆分,计算组数。

static void Main()
{
    long x = 0x1BD11BDAA9FC1A22; 
    var bitstring = Convert.ToString(x, 2) ;    
    Console.WriteLine("Bitstring: " + bitstring);
    var oneBitGroups = bitstring.Split(new char[]{'0'}, StringSplitOptions.RemoveEmptyEntries).Length;
    Console.WriteLine("The number of 1 bit groups is: " + oneBitGroups);
}

输出:

Bitstring: 1101111010001000110111101101010101001111111000001101000100010                                                                                                                                                                      
The number of 1 bit groups is: 16                                                                               

答案 1 :(得分:2)

你可以使用bitshift进行计数,并在每次最低有效位为1且前一次未进行计数时进行计数。

 V1           V2           V3           V4
1  HIAT1 3.917271e-05 4.278916e-05 3.793761e-05
2  SASS6 2.008972e-06 1.890391e-06 2.168946e-06
3 TRMT13 4.397712e-06 4.724036e-06 4.009512e-06

如果你跑

public static int BitGroupCount(long num)
{
    int count = 0;
    bool prevOne = false;
    while (num != 0)
    {
        bool currOne = (num & 1) == 1;
        if (currOne && !prevOne)
            count++;
        num = num >> 1;
        prevOne = currOne;
    }

    return count;
}

结果将得到16

答案 2 :(得分:0)

类似this之类的东西,可以将值作为二进制字符串获取:

int consecutive = 0;
char? previous = null;
foreach (char c in str)
{
    if (previous != null)
    {
        if (previous.Equals('1') && c.Equals('1'))
        {
            consecutive++;
        }
    }
    previous = c;
}
return consecutive;

答案 3 :(得分:0)

这应该有效:

ulong x = 0x1BD11BDAA9FC1A22UL;
bool last = false;
int count = 0;
for(int i = sizeof(ulong)*8-1; i >= 0; i--)
{
  var c = x & (1UL<<i);
  if(c != 0 && !last)
    count ++;
  last = c != 0;
}

count应为16

答案 4 :(得分:0)

我认为我找到了基于Hamming Weight的解决方案(感谢PetSerAl):

public static int no_of_consecutive_one_bits(ulong x)
{
    x = (x & ~(x << 1));
    x -= (x >> 1) & 0x5555555555555555;
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
    x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f;
    return ((int)((x * 0x0101010101010101) >> 56)); 
}

一些解释:x & ~(x<<1)基本上隔离了每个&#34;组&#34;中的最后一位。其余的是汉明加权算法,用于求和非零比特的数量。