Search code examples
pythonpython-3.xtype-conversionsignedunsigned-integer

How to convert a char to signed integer in python


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


Solution

  • 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; 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