遍历一个char位 [英] Iterating bits of a char
本文介绍了遍历一个char位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有字符C的ASCII code是 0110 0111
。我怎么可以遍历其位?我想建立从这些1的向量和0 ....
Assuming I have char "C" whose ascii code is 0110 0111
. How can I iterate over its bits? I would like to build a vector from these 1's and 0's....
推荐答案
您可以轻松地在他们使用按位运算符迭代:
You can easily iterate over them using bitwise operators:
char c = 'C';
for (int i = 0; i < 8; ++i)
{
// extract the i-th bit
int b = ((c & 1<<i) >> i);
// b will be 1 if i-th bit is set, 0 otherwise
// do whatever you want with b
}
您可以优化它(如在评论建议):
you can optimize it (as suggested in comments):
int b = ((c >> i) & 1);
这篇关于遍历一个char位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文