Ben Keshet
Ben Keshet

Reputation: 1

How to convert hexadecimal 2's complement to decimal in python

I am new to programming and python. I am struggling to find a consistent way to convert hexadecimal 2's complement to decimal. For example, find the decimal of 0xc001 and 0x7fff.

I have tried (H is the input):

  1. finding the inverse (0xffff - H)
  2. converting the inverse to decimal and subtracting 1.

That works with 0xc001 correctly, but doesn't work with 7fff. My control for correct answer is https://www.rapidtables.com/convert/number/hex-to-decimal.html

Example 0xc001:

  1. inverse is 0x3ffe (confirmed by converting to binary and flipping all bits)
  2. decimal -1 is -(16382) - 1 = -16383

However, with 7fff:

  1. inverse is 0x8000
  2. decimal -1 is -(32768) - 1 = -32769 which is incorrect (32767 is the correct answer)

appreciate a simple answer for beginners :)

thanks.

Upvotes: 0

Views: 659

Answers (0)

Related Questions