我正在用 C 编程进行编码。假设我有一个字符: char letter=0x0000; 所以字母的二进制数据现在是“00000000”假设我想将二进制数据更改为“10000000”,然后将其更改为“10010000”,是否有位运算符或方法可以让我更改“0”在特定位置到“1”或“1”到“0”。这也可能吗?
3 回答
如果您将任何位与 1 位进行异或,它会切换其值:
0 ^ 1 = 1
1 ^ 1 = 0
同样,如果您对任何位与 0 进行异或运算,它会保持相同的值:
0 ^ 0 = 0
1 ^ 0 = 1
因此,您可以通过与除位 n 以外的所有位置都为零位的数进行异或运算来翻转数的第 n 位:
val ^= (1 << n);
希望这可以帮助!
Yes it is very much possible. Just use bitwise exclusive OR or simply XOR operator on the number with 2 to the power of n where as n is the digit you want to change. ^ is the XOR operator in C.
000000 (decimal 0)
^ 100000 (decimal 32 = 2 power 5 = 1 << 5)
= 100000
1010 (decimal 10)
XOR 0010 (decimal 2 = 2 power 1 = 1 << 1)
= 1000
You can calculate 2 to the power of n by simply shifting bits in 1 by n bits. So 2 to the power of 4 can be obtained by shifting bits in 1 by 4 places.
inputNum ^ (1 << n) will give what you needed if toggling is all you need.
Bitwise XOR "^"
bit a bit b a ^ b (a XOR b)
0 0 0
0 1 1
1 0 1
1 1 0
However remember that doing XOR on a bit that already has 1 will convert it to zero. because 1 ^ 1 = 0;
If you just want to convert 0 to 1 and keep 1 if it is already there. You can have to use bitwise Or operator.
Bitwise OR "|"
bit a bit b a | b (a OR b)
0 0 0
0 1 1
1 0 1
1 1 1
Following is an example
11001110
| 10011000
= 11011110
Source: http://en.wikipedia.org/wiki/Bitwise_operations_in_C & http://en.wikipedia.org/wiki/Bitwise_operation
您可以使用按位与 (&) 和或 (|) 运算符。例如:
01001000 | 10111000 = 11111000
这是按照以下方式完成的: 72 | 184 = 248
(72 = 64+8)
有关详细信息,请参阅以下教程: http ://www.cprogramming.com/tutorial/bitwise_operators.html