[英]Invert 1 bit in C#
I have 1 bit in a byte
(always in the lowest order position) that I'd like to invert.我想反转一个
byte
1 位(始终处于最低顺序位置)。 ie given 00000001 I'd like to get 00000000 and with 00000000 I'd like 00000001.即给定 00000001 我想要 00000000 和 00000000 我想要 00000001。
I solved it like this:我是这样解决的:
bit > 0 ? 0 : 1;
I'm curious to see how else it could be done.我很想知道还有什么办法可以做到。
How about:怎么样:
bit ^= 1;
This simply XOR's the first bit with 1, which toggles it.这只是将第一位与 1 进行异或,从而切换它。
If you want to flip bit #N, counting from 0 on the right towards 7 on the left (for a byte), you can use this expression:如果你想翻转位#N,从右边的0到左边的7(一个字节),你可以使用这个表达式:
bit ^= (1 << N);
This won't disturb any other bits, but if the value is only ever going to be 0 or 1 in decimal value (ie. all other bits are 0), then the following can be used as well:这不会干扰任何其他位,但如果该值只是十进制值中的 0 或 1(即所有其他位均为 0),则也可以使用以下内容:
bit = 1 - bit;
Again, if there is only going to be one bit set, you can use the same value for 1 as in the first to flip bit #N:同样,如果只设置一个位,则可以使用与第一个翻转位 #N 中相同的 1 值:
bit = (1 << N) - bit;
Of course, at that point you're not actually doing bit-manipulation in the same sense.当然,在这一点上,您实际上并没有在同一意义上进行位操作。
The expression you have is fine as well, but again will manipulate the entire value.您拥有的表达式也很好,但同样会操纵整个值。
Also, if you had expressed a single bit as a bool
value, you could do this:此外,如果您将一个位表示为
bool
值,您可以这样做:
bit = !bit;
Which toggles the value.哪个切换值。
More of a joke : Of course, the "enterprisey" way would be to use a lookup table:更多的是一个笑话:当然,“企业”方式是使用查找表:
byte[] bitTranslations = new byte[256];
bitTranslations[0] = 1;
bitTranslations[1] = 0;
bit = bitTranslations[bit];
Your solution isn't correct because if bit == 2 (10) then your assignment will yield bit == 0 (00).您的解决方案不正确,因为如果 bit == 2 (10) 那么您的分配将产生 bit == 0 (00)。
This is what you want:这就是你想要的:
bit ^= 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.