Bitwise NOT Operator


#1

I understand binary pretty well and I can work out all of the other operators by hand because I already had prior knowledge on binary and operators, but I really don't understand that math behind the NOT operator and the lesson that it talks about it in,
https://www.codecademy.com/en/courses/python-intermediate-en-KE1UJ/1/5?curriculum_id=4f89dab3d788890003000096
states that they won't explain it because it is complicated math. Because I understand math and binary pretty well, I think that I can for sure grasp the concept of the operator and how it works, but I just wanted to know if anybody could explain it more in depth and the algorithm for it. I can do the first part, turning all the 1's into 0's and vice versa, but I know that's not the rest of it. You have to know how to deal with a negative number, do some more flipping, and add a one at the end. As you can see, my understanding of it is very slim and I know the outcome of it, but I would like to know the process, more out of curiousity than anything else. :slight_smile:
Thanks!


#2

Bitwise NOT gives the two's complement of a number. Rather than trying to explain, let's turn to Wikipedia...


#3

Aha! Thank you so much! My dad told me that two's complement was what was going on, but I just was really confused because I had no idea what that was so this helps a lot! :smile:


#4

Python behaves differently from languages that use fixed-width integers, python's int can be of arbitrary size so negative numbers therefore have an infinite amount of leading ones in their binary representations. If you print them then they'll simply print as the positive version with a unary -, same as is done with with decimal numbers (-5, -0b101).

..well, I suppose it behaves the same if you only look at the same bits

>>> bin(-1)
'-0b1'
>>> bin(-1 & 1023)
'0b1111111111'

#5

That's really cool actually, I didn't know that in python that the integer could be more than 4
(edit: bytes). I know in Java that it cannot, but I guess python's easier in most things - at least for me.


#6

there are 8 bits in a byte, java's int is 4 bytes


#7

whoops, you're right, I forget constantly. I've had the math explained before too.