如何在C++中通过长long逐位循环
How to loop bit by bit over a long long in C++
如果我在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
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 在c++中,未使用的"new long"循环之后的所有内容都运行得更快
- 如何在C++中通过长long逐位循环
- 奇怪的并行循环行为 int v long int
- 当运行long-for循环的小部件(QDialog)在没有多线程的情况下关闭时,我如何停止它