two's complement in Python

Two's Complement binary for Negative Integers:

Negative numbers are written with a leading one instead of a leading zero. So if you are using only 8 bits for your twos-complement numbers, then you treat patterns from 00000000 to 01111111 as the whole numbers from 0 to 127, and reserve 1xxxxxxx for writing negative numbers.

Thus, -1 is complement(1 - 1) = complement(0) = 11111111.
Or complement(1) + 1 = 11111110 + 1 = 11111111.

This means that negative numbers go all the way down to -128 = complement(127) = -128 (10000000).

Python has switched to using an INFINITE number of bits. Thus the number -5 is treated by bitwise operators as if it were written ...1111111111111111111011"].

-128, -127,...,-1, 0,1,2,...,127

0 -> flip -> -1
1 -> flip -> -2
2 -> flip -> -3
...
...
127 -> flip -> -128
# 32 bits integer max
max = 0x7FFFFFFF
# 32 bits interger min
min = 0x80000000
mask = 0xFFFFFFFF
# convert the negative num to 2's complement with 32 bits 
def convertNegative32bits(num):
  n = abs(num)
  mask = 0xffffffff
  if num < 0:
    n = (n - 1) ^ mask # minus 1 and flip it
    return n
# or
def convertNegative32bits(num):
  n = abs(num) # convert it to positive 
  mask = 0xffffffff
  if num < 0:
    n = 1 + (n ^ mask) # flip it and plus 1
    return n

# or
def convertNegative32bits(num):
   mask = 0xffffffff
   return num & mask # just & mask

Reference: https://wiki.python.org/moin/BitwiseOperators

你可能感兴趣的:(two's complement in Python)