1

I am writing an algorithm in a limited language where the bitwise operators at my disposal are

  • AND: &
  • OR: |
  • XOR: ^
  • SRL: << (shift left)
  • SLL: >> (shift right)

I realized I need to be able to take the bitwise complement of an integer, commonly denoted ~x in other languages.

Could I somehow express ~x, using only the {&, |, ^, <<, >>} operators?

I would try to just implement this operator in the language’s compiler, but it seems like a very challenging task. I would much rather do some dirty hack to express NOT x without ~.

bp99
  • 338
  • 3
  • 15
  • Well, I suppose I could just convert the value to an array of binary values, flip them in a loop and then convert the array back into an integer… I wish there were a simpler solution though – bp99 Oct 20 '21 at 15:06
  • 3
    XOR with -1? (Or whatever numeric constant has an all-1-bits representation on your system.) – jasonharper Oct 20 '21 at 15:06
  • @jasonharper a simple XOR with an all-1-bits number is indeed the solution. What a shame, apparently my brain is toast. Thanks! – bp99 Oct 20 '21 at 15:13
  • Please add your comment as an actual answer so I can select it as the accepted answer. – bp99 Oct 20 '21 at 15:14

0 Answers0