循环通过C位 [英] Looping through Bits C
本文介绍了循环通过C位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图遍历无符号字符的位,但是我不确定从哪里开始,最终,我将对这些位执行其他按位运算,例如〜和xor..etc.
I'm trying to loop through the bits of an unsigned char, but I'm not sure where to start, eventually, I'll perform other bitwise operating on the bits, such as ~ and xor..etc.
推荐答案
可以通过以下几种方法进行位循环:
Looping over bits can be done in several ways:
- 当您移动值并根据枚举位的顺序测试初始或最终位时,您可以进行破坏性循环,或者
- 当您使用按位AND并通过左移
1
产生的单个 mask 来测试数字时,可以执行非破坏性循环.
- You can do a destructive loop, when you shift the value, and test the initial or the final bit, depending on the order in which you would like to enumerate bits, or
- You can do a non-destructive loop, when you use bitwise AND to test the number with a single-bit mask, produced by left-shifting
1
.
以下是第一种方法的示例:
Here is an example of the first approach:
unsigned int bits = ...;
while (bits) {
if (bits & 1) {
// Current bit is set to 1
} else {
// Current bit is set to 0
}
bits >>= 1;
}
如果要在达到零后继续使用位,请另作一个计数器.
If you want to continue working with bits after you reach zero, make a separate counter.
以下是第二种方法的示例:
Here is an example of the second approach:
unsigned int bits = ...;
for (int pos = 0 ; pos != 16 ; pos++) {
if (bits & (1 << pos)) {
// Current bit is set to 1
} else {
// Current bit is set to 0
}
}
这篇关于循环通过C位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文