在C#中反转1位 [英] Invert 1 bit in C#

查看:77
本文介绍了在C#中反转1位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要反转的byte中有1位(始终位于最低位). 即给定00000001,我想得到00000000,而有了00000000,我想得到00000001.

I have 1 bit in a byte (always in the lowest order position) that I'd like to invert. ie given 00000001 I'd like to get 00000000 and with 00000000 I'd like 00000001.

我这样解决了它:

bit > 0 ? 0 : 1;

我很好奇,看看还能怎么做.

I'm curious to see how else it could be done.

推荐答案

怎么样:

bit ^= 1;

这仅仅是XOR与1的第一位,它将对其进行切换.

This simply XOR's the first bit with 1, which toggles it.

如果要翻转#N位(从右边的0到左边的7(对于一个字节)计数),可以使用以下表达式:

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:

bit ^= (1 << N);

这不会打扰其他任何位,但是如果该值只能是十进制值的0或1(即所有其他位均为0),那么也可以使用以下内容:

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:

bit = 1 - bit;

同样,如果只设置一个位,则可以使用与第一个翻转位#N相同的值来设置1:

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:

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.

此外,如果您将单个位表示为bool值,则可以执行以下操作:

Also, if you had expressed a single bit as a bool value, you could do this:

bit = !bit;

切换值.

更多的笑话: 当然,"enterprisey"方式将是使用查找表:

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];

这篇关于在C#中反转1位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆