Java 如何在任何语言的整数中的特定位置翻转位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18247126/
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
how to flip a bit at a specific position in an integer in any language
提问by
I have an integer n
, and I want to flip its k
th bit (from the lowest) in its binary representation. How can I do it?
我有一个 integer n
,我想k
在其二进制表示中翻转它的第 th 位(从最低位)。我该怎么做?
For example, if I have n=0b01101
and k=2
, then the result is 0b01001=9
例如,如果我有n=0b01101
and k=2
,那么结果是0b01001=9
Any language is fine. Thank you.
任何语言都可以。谢谢你。
回答by NPE
To flip one or more bits, use binary XOR. In your case, the appropriate XOR mask is 1
shiftedk
bits to the left.
要翻转一位或多位,请使用二进制 XOR。在您的情况下,适当的 XOR 掩码向左1
移位k
。
In Python:
在 Python 中:
In [58]: 0b01101 ^ (1 << 2)
Out[58]: 9
The expression:
表达方式:
n ^ (1 << k)
is valid in C, Java, Python and a few other languages (provided the variables are appropriately defined).
在 C、Java、Python 和一些其他语言中有效(前提是变量被适当地定义)。
回答by Kevin
Here's how you'd do it in C:
下面是你在 C 中的做法:
n ^ (1 << k)
回答by Constablebrew
Left-shift the number 1 the number of digits you need, and then XOR the number.
将数字 1 左移所需的位数,然后对数字进行异或。
JavaScript:
JavaScript:
var num = 6, k = 2;
num = num ^ (1 << k);
What is happening:
怎么了:
num = 0b01101 XOR (0b00001 << 2)
num = 0b01101 XOR 0b00100
num = 0b01001
回答by Ion
In c you just do this to toggle it:
在 c 中,您只需执行以下操作即可切换它:
n ^= 1 << k;
but there are other ways of doing it like:
但还有其他方法可以做到:
n |= ( 1 << k);
This shifts bit k to 1
这将位 k 移至 1
Now if you want to flip the bit you can do an if statement with a unary and to see how you need to flip it
现在如果你想翻转位,你可以用一元做一个 if 语句,看看你需要如何翻转它
number = pow(2,k)
if((number & n) != number)
//this means that it's a 0 at position k
n |= ( 1 << k);
else
//this means that it's a 1 at position k
n &= ( 0 << k);