Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ~3 equal to -4 in Python?

I'm getting started in Python programming. I'm reading a basic tutorial, but this point is not very clear to me. I would appreciate any help you can give me.

like image 951
elgianka Avatar asked Dec 10 '25 22:12

elgianka


2 Answers

~3 means 'invert' 3. With two's complement on natural number datatypes, this becomes -4, as the binary representation is inverted (all bits are flipped).

like image 151
Chris Dennett Avatar answered Dec 14 '25 16:12

Chris Dennett


~3 means "change all the 1s to 0s and 0s to 1s", so if 3 in binary is 0000000000000011, then ~3 is 1111111111111100. since the first bit of ~3 is a 1, its a negative number. to find out which negative number, in 2s comliment, you invert all bits and add 1, so inverted we are back to 3, then added 1 we get 4.

like image 43
stew Avatar answered Dec 14 '25 17:12

stew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!