访问 char c++ 中的单个位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9531214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access individual bits in a char c++
提问by AnotherProgrammer
How would i go about accessing the individual bits inside a c++ type, char
or any c++ other type for example.
例如,我将如何访问 C++ 类型char
或任何 C++ 其他类型中的各个位 。
回答by Matt
If you want access bit N
:
如果你想访问位N
:
Get: (INPUT >> N) & 1;
得到: (INPUT >> N) & 1;
Set: INPUT |= 1 << N;
放: INPUT |= 1 << N;
Unset: INPUT &= ~(1 << N);
取消设置: INPUT &= ~(1 << N);
Toggle: INPUT ^= 1 << N;
切换: INPUT ^= 1 << N;
回答by qdii
You would use the binary operators |
(or), &
(and) and ^
(xor) to set them. To set the third bit of variable a
, you would type, for instance:?
您可以使用二元运算符|
(or)、&
(and) 和^
(xor) 来设置它们。要设置 variable 的第三位a
,您可以输入,例如:?
a = a | 0x4
// c++ 14
a = a | 0b0100
Note that 4's binary representation is 0100
注意 4 的二进制表示是 0100
回答by brut3f0rc3
That is very easy Lets say you need to access individual bits of an integer Create a mask like this int mask =1; now, anding your numberwith this mask gives the value set at the zeroth bit in order to access the bit set at ith position (indexes start from zero) , just and with (mask<
这很容易 假设您需要访问整数的各个位 创建一个像这样的掩码 int mask =1; 现在,将您的数字与此掩码一起给出设置在第零位的值,以便访问在第 i 个位置设置的位(索引从零开始),只需并使用 (mask<