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.

Scenario

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) {
    sb.append(b);
    //this one is better choice
    //sb.append(String.format("%02X ", b));
}
return sb.toString();


Sample output 
12333-124-118-55-8153-6613-3745107-97-61-1232552-37-12432

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.

Solution-1

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)
else:
    return byte

Solution-2

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