Search code examples
c#bit-manipulation32-bitbinary-operators

Inverting all 32 bits in a number using binary operators in c#


I am wondering how you take a number (for example 9), convert it to a 32 int (00000000000000000000000000001001), then invert or flip every bit (11111111111111111111111111110110) so that the zeroes become ones and the ones become zeroes.

I know how to do that by replacing the numbers in a string, but I need to know how to do that with binary operators on a binary number.

I think you have to use this operator, "~", but it just gives me a negative number when I use it on a value.


Solution

  • If you look at the decimal version of your number then its a negative number. If you declare it as a unsigned int then its a positive one. But this doesnt matter, binary it will always be 11111111111111111111111111110110. Try this:

    int number = 9;
    Console.WriteLine(Convert.ToString(number, 2)); //Gives you 1001
    number = ~number;                               //Invert all bits
    Console.WriteLine(Convert.ToString(number, 2));
    //Gives you  your wanted result: 11111111111111111111111111110110