I’m a little confused by the ~ operator. Code goes below:
a = 1
~a #-2
b = 15
~b #-16
How does ~ do work?
I thought, ~a would be something like:
0001 = a
1110 = ~a
why not?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You are exactly right. It’s an artifact of two’s complement integer representation.
In 16 bits, 1 is represented as
0000 0000 0000 0001. Inverted, you get1111 1111 1111 1110, which is -2. Similarly, 15 is0000 0000 0000 1111. Inverted, you get1111 1111 1111 0000, which is -16.In general,
~n = -n - 1