views:

234

answers:

2
+11  Q: 

Invert 1 bit in C#

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.

I solved it like this:

bit > 0 ? 0 : 1;

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

+20  A: 

How about:

bit ^= 1;

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

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

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;

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.

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

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];
Lasse V. Karlsen
This has the advantage of not requiring the first bit to be selected first, as well.
Will Vousden
I first wanted to use ! but then discovered it's only for bools. Fun stuff, working at this level.
Matt Jacobsen
I'd second the 'expressing it as a bool' argument - depending on what you are doing, may make the code a little easier to read for the next guy to maintain.
Paddy
if I use bool then I have to cast it all the time.
Matt Jacobsen
+1 Great answer, good joke :)
Brian Rasmussen
+2  A: 

Your solution isn't correct because if bit == 2 (10) then your assignment will yield bit == 0 (00).

This is what you want:

bit ^= 1;

par
You're right, but I've already shifted the bit to the lowest order so this isn't a problem for me
Matt Jacobsen
If all you're trying to do is test/manipulate that one bit you can get rid of the shift operation and just xor it in-place with a different constant (e.g. if it was the 7th most significant bit you do something like bit ^= 0x40;)
par