How to Convert Two’s Complement to Decimal in Python?

Estimated read time 1 min read

To convert a two’s complement binary number to decimal in Python, you can use the following steps:

  1. Obtain the binary representation of the two’s complement number.
  2. Check if the number is negative by examining the most significant bit (MSB). If the MSB is 1, the number is negative.
  3. If the number is negative, invert all the bits and add 1 to the resulting value.
  4. Convert the resulting binary value to decimal using the int() function with the base argument set to 2.

Here’s an example Python function that performs the conversion:

def twos_complement_to_decimal(binary):
    if binary[0] == '1':  # Check if the number is negative
        inverted = ''.join('1' if bit == '0' else '0' for bit in binary)  # Invert the bits
        decimal = -(int(inverted, 2) + 1)  # Convert to decimal and add 1
        decimal = int(binary, 2)  # Convert to decimal

    return decimal

You can use this function by passing the two’s complement binary number as a string argument, like this:

binary_number = '1111111111111110'  # Example two's complement binary number
decimal_number = twos_complement_to_decimal(binary_number)

This will output the decimal representation of the two’s complement number.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply