The question doesn't clearly state if the single character is given as str
or bytes
.
The following answer is especially useful, if the input is an instance of bytes
:
Since Python 3.2 there is a class method int.from_bytes
:
int.from_bytes(b'\x81', byteorder='big', signed=True) # -127
int.from_bytes(b'a', byteorder='big', signed=True) # 97
For 16-bit integers, one would simply pass 2 bytes instead of 1:
int.from_bytes(b'\x81\x80', byteorder='big', signed=True) # -32384
int.from_bytes(b'ab', byteorder='big', signed=True) # 24930
Of course, you may need to specify byteorder='little'
.
However, if the input is an ASCII character (0 - 128), I don't understand why you want a signed integer, because the result for your input will always be positive anyway (if I'm not mistaken). Python's integers use a flexible amount of bytes.