Othman
Othman

Reputation: 9

How to convert a hex string to signed integer in Python

In the following example I can convert a string to unsigned integer, but I need a signed integer. How can I convert a char to signed integer?

s = "bd"
d = int(s, 16)
print(d)

The Result is 189, but I expect -67.

Upvotes: 0

Views: 1415

Answers (2)

orithena
orithena

Reputation: 1485

The main problem is that int() cannot know how long the input is supposed to be; or in other words: it cannot know which bit is the MSB (most significant bit) designating the sign. In python, int just means "an integer, i.e. any whole number". There is no defined bit size of numbers, unlike in C.

For int(), the inputs 000000bd and bd therefore are the same; and the sign is determined by the presence or absence of a - prefix.

For arbitrary bit count of your input numbers (not only the standard 8, 16, 32, ...), you will need to do the two-complement conversion step manually, and tell it the supposed input size. (In C, you would do that implicitely by assigning the conversion result to an integer variable of the target bit size).

def hex_to_signed_number(s, width_in_bits):
    n = int(s, 16) & (pow(2, width_in_bits) - 1)
    if( n >= pow(2, width_in_bits-1) ):
        n -= pow(2, width_in_bits)
    return n

Some testcases for that function:

In [6]: hex_to_signed_number("bd", 8)
Out[6]: -67

In [7]: hex_to_signed_number("bd", 16)
Out[7]: 189

In [8]: hex_to_signed_number("80bd", 16)
Out[8]: -32579

In [9]: hex_to_signed_number("7fff", 16)
Out[9]: 32767

In [10]: hex_to_signed_number("8000", 16)
Out[10]: -32768

Upvotes: 3

Manjari
Manjari

Reputation: 332

print(int.from_bytes(bytes.fromhex("bd"), byteorder="big", signed=True))

You can convert the string into Bytes and then convert bytes to int by adding signed to True which will give you negative integer value.

Upvotes: 2

Related Questions