1

I wanted to ask if there is an efficient way to inverse all set and unset bits in an integer. For example: If I have the integer:

1338842

this is the same in binary as this:

101000110110111011010

How can I inverse this so every 1 bit becomes a 0 bit and every 0 bit becomes a 1 bit. The reversed result then should be:

010111001001000100101

which is basically the integer:

758309

Unfortunately I can't show my attempt because I don't have any. I don't know how to do this. Thats why I hope someone from the board can give me some advice.

Dark Side
  • 695
  • 2
  • 8
  • 18

2 Answers2

10

This is exactly what the bitwise not operator (~) does.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
7

bitwise operators!

int value = 1338842;
int inversed = ~value;
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37