C# 一种反转整数变量二进制值的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19712206/
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
A way to invert the binary value of a integer variable
提问by Martin Dzhonov
I have this integer int nine = 9;
which in binary is 1001
. Is there an easy way to invert it so I can get 0110
?
我有这个整数int nine = 9;
,二进制是1001
. 有没有一种简单的方法可以反转它以便我可以得到0110
?
回答by sh1ng
Use xor with 111111....
对 111111 使用异或......
var inverted = a ^ int.MinValue
回答by Servy
There's an operator specifically for it, ~
.
有一个专门用于它的运算符,~
.
nine = ~nine;
回答by Scott Mermelstein
int notnine = ~nine;
If you're worried about only the last byte:
如果您只担心最后一个字节:
int notnine = ~nine & 0x000000FF;
And if you're only interested in the last nibble:
如果您只对最后一点感兴趣:
int notnine = ~nine & 0x0000000F;
The ~ operatoris the bitwise negation, while the mask gives you only the byte/nibble you care about.
该〜运算符是按位取反,而面具只给你字节/轻咬你所关心的。
If you truly are interested in only the last nibble, the mostsimple is:
如果你真的只对最后一点感兴趣,最简单的是:
int notnine = 15 - nine;
Works for every nibble. :-)
适用于每一口。:-)
回答by Bas
If we consider 9 as an integer like this:
如果我们将 9 视为这样的整数:
00000000000000000000000000001001
and you want to have:
并且你想要:
00000000000000000000000000000110
instead of:
代替:
11111111111111111111111111110110
And do care about more than the last nibble (e.g. also want to handle 128903).
并且确实关心比最后一个半字节更多(例如还想处理 128903)。
Then you can create a mask and apply it:
然后你可以创建一个蒙版并应用它:
uint value = 9; //or try 1290320
uint mask = 0;
for (int i = 1; i <= 16; i *= 2)
mask |= mask >> i;
value = mask & (~value);
You could speed this up using a modified version of http://en.wikipedia.org/wiki/Find_first_set, or using the bsf asm instruction.
您可以使用http://en.wikipedia.org/wiki/Find_first_set的修改版本或使用 bsf asm 指令来加快速度。
回答by Mark Ransom
This problem is not completely specified - do you only care about 4 bits, or should the answer adjust to the number of significant bits in the input? If it's the latter then you'll need some sophisticated bit manipulation to mask off the upper bits.
这个问题没有完全指定 - 你只关心 4 位,还是应该根据输入中的有效位数调整答案?如果是后者,那么您将需要一些复杂的位操作来屏蔽高位。
I'll slightly modify a Bit Twiddling Hackto create the mask.
我将稍微修改一个Bit Twiddling Hack来创建蒙版。
int mask = num;
mask |= mask >> 1;
mask |= mask >> 2;
mask |= mask >> 4;
mask |= mask >> 8;
mask |= mask >> 16;
int inverse = ~num & mask;
See it in action: http://ideone.com/pEqwwM
看到它在行动:http: //ideone.com/pEqwwM
回答by Kuba
1) Create a mask for the last n bits that you want to flip
1) 为要翻转的最后 n 位创建掩码
mask = (1<<n) - 1
2) use xor
2)使用异或
a ^ mask
Additionally if you want to flip bits starting from the first 1 in binary representation you can do this
此外,如果您想从二进制表示中的第一个 1 开始翻转位,您可以这样做
n = 0; while ((1<<n) <= a) n++;