Python invert operator - visualizing the negative number -
in simple words, definition given ~n -n - 1.
for example ~1
1 = 0001 ~1 = 1110 (which -2)
for numbers
say ~2
2 = 0010 ~2 = 1101 (which representation of -3 in twos complement)
but question is
1110 = -2 can visualized -2 (the right 2 bits 10 , rest 1) 1101 = -3 can't visualized (going above logic should -5)
so wondering there simple way see , tell twos complement binary negative number represents without doing calculations .
~n = -n - 1
equivalent -n = ~n + 1
. means figure out negative of number is, can invert (in head) , add one. pretend zeros ones , vice versa, add one.
example: pretend this
1101
is this
0010
then add 1
0011
thus, 1101
represents -3
.
Comments
Post a Comment