December 04, 2017

Converting Binary↔Decimal of two's complement with Python

At the time of writing this post, because the converting python code based on two's complement(Learn more) is unfavorable, i wrote this post.

Below is a Python code based on two's complement, which converts binary numbers to decimal numbers and decimal numbers to binary numbers.

As a precaution, the "digit" parameter of twoCom_binDec is not the length of the inputted binary number. It is the length of the bit that the system uses to store the inputted data.




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(dec-pow(2,digit)).split("0b")[1]

e.g.
>>>twosCom_binDec("11100101", 8)
-27 <type 'int'>

>>>twosCom_decBin(27, 8)
00011011 <type 'str'>

>>>twosCom_decBin(-27, 8)
11100101 <type 'str'>