I don't have much experience with Python, so I need your help! In the following example I can convert a char to unsigned integer, but i need a signed integer. How can I convert a char to signed integer in python?
d="bd"
d=int(d,16)
print (d)
The Result is: 189 but I expect: -67
CodePudding user response:
First a nitpick: It's not a char, it's a string.
The main problem is that int()
cannot know how long the input is supposed to be. 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; e.g.:
def hex_to_signed_number(s, width_in_bits):
n = int(s, 16)
while( 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
CodePudding user response:
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.