Two’s complement is a system that allows a binary number to be reversibly converted into a number with an equivalent value but negative.
The process
- Find the positive binary value for the negative number you are looking to represent.
- Add a leading
0
to the front of the number to show it is positive. - Invert each bit in the number
- Add 1 to the number
Example:
Denary number: 10 Binary Equivalent: 1010
01010
10101
10101
Result: 10110
Python representation
A fairly rudimentary representation of this algorithmically is as follows. It isn’t perfect and has flaws - but it does the job a decent chunk of the time. Issues are included in the comments.