[英]How to loop bit by bit over a long long in C++
如果我有long long x;
在 C++ 中,如何遍歷數字中的每一位以檢查它是 0 還是 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.