0

I'm trying to turn 1's into 0's and vice versa of a binary number, and I thought bitwise NOT (~) would do the job as I've done it before on C code, but it doesn't work like that on Python.

Example

I have a binary 'a' a= 0b1010 = 10

I used '~' and I get this: ~a=-0b1011 = -11

But I want this: ~a=0b0101 = 5

what is the right way to do it?

THANKS!

  • 5
    It's doing exactly what you want. It's just that Python integers use unlimited precision, so the complement of a non-negative integer contains an infinite number of leading 1 bits. Python treats these as two's complement values, so it interprets them as negative numbers. So `~0b1010` is `0b1111.....111110101`, which in two's complement is just `-11`. If you want to mask off the high-order bits, just do a bitwise AND with one less than the desired power of two. – Tom Karzes Sep 28 '21 at 03:03
  • 1
    Something like `~a & (a.bit_length() ** 2 - 1)` should work – Iain Shelvington Sep 28 '21 at 03:09
  • 3
    @IainShelvington You meant `2**a.bit_length()`, not `a.bit_length()**2`. Of course, it's simpler and more efficient to use `1< – Tom Karzes Sep 28 '21 at 03:13
  • @TomKarzes Thanks, yes I did. Annoyingly `4**2 == 2**4`, so my quick test passed – Iain Shelvington Sep 28 '21 at 03:15
  • @TomKarzes: good explanation - is there a canonical answer for that? There's [this one](https://stackoverflow.com/questions/55145028/binary-ones-complement-in-python-3) but it doesn't cover masking the higher bits. – sj95126 Sep 28 '21 at 03:32
  • Does this answer your question? [How do I do a bitwise Not operation in Python?](https://stackoverflow.com/questions/31151107/how-do-i-do-a-bitwise-not-operation-in-python) – Tom Karzes Sep 28 '21 at 03:40
  • @sj95126 It looks like the above covers it. – Tom Karzes Sep 28 '21 at 03:41

0 Answers0