-1

Is there a function that takes a number with binary numeral a, and does the NOT?

(For example, the function's value at 18 [binary 10010] would be 13 [binary 01101].) I thought this was what the tilde operator (~) did, but it only adds a minus sign to 18, which is two's complement of that, instead of getting 13.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Likak
  • 373
  • 1
  • 5
  • 19
  • 5
    Are you _sure_ that `~18` is `-18`. Are you really sure? I get `-19` – Eric Jan 31 '17 at 21:16
  • try `13 ^ 0b11111` – Jean-François Fabre Jan 31 '17 at 21:16
  • 3
    `~` is bitwise NOT. Specifically, for standard Python ints, it's signed, bignum bitwise NOT. You seem to be expecting 5-bit unsigned bitwise NOT, for some reason. – user2357112 Jan 31 '17 at 21:17
  • 2
    What would you expect the output to be for input 13? Would you expect 2, or 18? If 18, why are you putting exactly one leading zero on 13? – user2357112 Jan 31 '17 at 21:18
  • Suppose it worked the way you showed. Then what is 13, is it really 01101, or is it 1101? Shouldn't it be 1101, given that 18 was 10010 and did not have a mysterious 0 in front of it? If it was bitwise-notted again, should it go back to 18, or to 2? Anyway I put it to you that none of these options make sense, the only thing that's really sensible is to invert *all* bits even if they are to the left of the leftmost set bit, which is the only definition that works well together with the other bitwise (and even arithmetic) operations. – harold Jan 31 '17 at 21:27
  • I linked this to the canonical duplicate to explain what `~` does - it is, in fact, the sought-after bitwise NOT operator - and added an answer there to explain why the expected result here is mistaken, and how to get it anyway. – Karl Knechtel Jan 07 '23 at 02:42

1 Answers1

5

As mentioned in the comments ~ is the bitwise NOT.

If you want a 5 bit unsigned bitwise NOT you can use an XOR with a mask:

>>> n = 0b10010 # 18
>>> m = 0b11111
>>> n ^ m
13
Andrew Jenkins
  • 1,590
  • 13
  • 16