Convert 8-bit byte to signed int in python

Last updated on by michaelyin

Python has provided library to handle bit maniputation in most cases, however, I can not find a good way to convert a 8-bit single byte to signed int type using built-in lib.


Here is scenario, some newbie Java developer need to hash the password and save it to database, he did not convert to hash result to hex string but just called toString to save it to database.

The Java code is like this

StringBuilder sb = new StringBuilder();
for (byte b : strBytes) {
    //this one is better choice
    //sb.append(String.format("%02X ", b));
return sb.toString();

Sample output 

Byte in Java is represented by signed int in range (-128, 127), Byte Python is represented by unsigned int in range(0, 255). So I nedd to convert the 8-bit byte in python to signed int to make comparison done.


Since java use one bit to mark sign, so we can make it without using 3-party lib

if byte > 127:
    return (256-byte) * (-1)
    return byte


There are some 3-party lib to provide good support to bit maniputation. bitstring is recommended by me, you can use it to work in bit.

bit = bitstring.Bits(uint=byte, length=8)
print bit.unpack('int')

Quite simple! And you can dive in deeper to find other good feature

Send Me Message

Tell me more about your project and see if I can help you.

Contact Me