New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Python uses two different methods for Tilde operator. #113617
Comments
|
Hello! >>> import operator
>>> operator.neg(60)
-60Changing it would be break backward compatibility with a lot of python code. |
|
Hi @mohamadiarch , I think you confuse couple of things:
Under the hood, signed integers are represented in 2’s complement format. When you perform Negation of signed integer This is why
Not only that but whole integer system in general :) |
|
@WolframAlph Can you break it down with an example 60? I think if we use |
|
@mohamadiarch,
Makes sense? Flipping bits of some integer and negating integer is not the same. Please, read through my explanation carefully. |
|
@WolframAlph I have understood your formula. But what I can't figure out is the method of going from binary to decimal. You use the formula for the final answer and get |
Correct.
Wrong. Have you read what I wrote earlier?
So yes, you can interpret
Interpretation depends on context. In this scenario context is that |
|
invert operator ~: "The bitwise inversion of x is defined as -(x+1). " @mohamadiarch In the future, please consult the docs. A place to discuss such details is https://discuss.python.org/c/users/7. |
|
@WolframAlph I made a mistake. I'm sorry, I shouldn't have said that in this place. Thank you for your explanation. Your explanation was perfect. |
Bug report
Bug description:
I think there is a small bug in Python.
How does it work? I think we can break it down into three steps:

First step: Convert
60to binary:00111100.Second step: it converts zeros to ones and vice versa. so we would have
11000011.Finally, it should convert binary to decimal and Python will print
-61, but that's wrong. Because Python thinks it's a two's complement number, but it's not, Python has forgotten that it's a one's complement number, we just convert ones and zeros to each other and nothing else, and that's a one's complement number. This means that Python uses the one's complement method in the second step and uses another method (the two's complement method) for converting to decimal number in the final step. And I think this is wrong, we should use one method for both steps. And if we use the one's complement to decimal method, the answer should be-60and not-61.CPython versions tested on:
3.12
Operating systems tested on:
Windows
The text was updated successfully, but these errors were encountered: