如何在C++中通过长long逐位循环

How to loop bit by bit over a long long in C++

本文关键字:long 循环 C++      更新时间:2023-10-16

如果我在c++中有long long x;,我如何循环数字中的每个位以检查它是零还是1?

我想数一下比特中的1的数量。

您需要使用移位>>运算符:

unsigned long long x = static_cast<unsigned long long>(your_value);
//unsigned long long fix for issue pointed out by @Zac Howland in comments
unsigned int count = 0;//number of 1 bits
while (x != 0)
{
    unsigned long long bit = x & 1;
    if( bit == 1 )
    {
        count ++;//...
    }
    else //zero
    {
        //...
    }
    x >>= 1;
}

还有其他方法可以通过各种方式实现这一点,您可以在这里找到它们(以及其他东西)

您不需要执行移位操作。:)

size_t count = 0;
for ( long long v = x; v; v &= v - 1 ) ++count;
const unsigned int BITCOUNT = sizeof(long long) * CHAR_BIT - 1;
// or
const unsigned int BITCOUNT = sizeof(unsigned long long) * CHAR_BIT;
for (unsigned int i = 0; i < BITCOUNT; ++i)
{
    unsigned int test_bit = 1LL << i;
    if (value & test_bit)
    {
        // do something
    }
}

如果你只想要比特计数,你可以使用SWAR算法:

unsigned int bit_count(unsigned long long i)
{
    i = i - ((i >> 1) & 0x5555555555555555);
    i = (i & 0x3333333333333333) + ((i >> 2) & 0x3333333333333333);
    return (((i + (i >> 4)) & 0x0F0F0F0F0F0F0F0F) * 0x0101010101010101) >> 56;
}

以下程序显示了用于循环通过字节的过程

#include <iostream>
int main()
{
    std::uint_fast8_t flags{ 0b10011000 };
    for (int i = 128; i >= 1; i /= 2)
    {
        if (flags & i)
            std::cout << '1';
        else
            std::cout << '0';
    }
    std::cout << 'n';
    return 0;
}

此打印:10011000