Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert 1 bit in C#

Tags:

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.

like image 439
Matt Jacobsen Avatar asked Apr 09 '10 08:04

Matt Jacobsen


People also ask

How do you flip all bits?

Here we use the flip() of bitset to invert the bits of the number, in order to avoid flipping the leading zeroes in the binary representation of the number, we have calculated the number of bits in the binary representation and flipped only the actual bits of the number.

What is the inverse of a bit?

In telecommunications, bit inversion means the changing of the state of a bit to the opposite state, i.e. the changing of a 0 bit to 1 or of a 1 bit to 0. It also refers to the changing of a state representing a given bit to the opposite state.

What is flip in C?

Flipping a bit denotes switching or reversing the existing bit. The technique of analytically rearranging bits or other elements of data smaller than even a byte is known as bit manipulation. The C programming language is proficient at handling bits.


1 Answers

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]; 
like image 106
Lasse V. Karlsen Avatar answered Oct 04 '22 22:10

Lasse V. Karlsen