February 19, 2018

Two's complement Python code

I wanted to use 2's complement in Python, but I could not find a related function, so I made This code.

<Twos_complement.py>

def twosCom_binDec(bin, digit):
  while len(bin)<digit :
    bin = '0'+bin
  if bin[0] == '0':
    return int(bin, 2)
  else:
    return -1 * (int(''.join('1' if x == '0' else '0' for x in bin), 2) + 1)


def twosCom_decBin(dec, digit):
  if dec>=0:
    bin1 = bin(dec).split("0b")[1]
    while len(bin1)<digit :
      bin1 = '0'+bin1
    return bin1
  else:
    bin1 = -1*dec
    return bin(bin1-pow(2,digit)).split("0b")[1]

[How to use]
twosCom_decBin(502, 16)  →  "0000000111110110"
twosCom_decBin(-502, 16)  →  "1111111000001010"
twosCom_binDec("1111111000001010", 16)  →  "-502"

twosCom_decBin(27, 8)  →  "00011011"
twosCom_decBin(-27, 8)  →  "11100101"
twosCom_binDec("11100101", 8)  →  "-27"