Adding bits cause wrong number when first byte is zero

Viewed 47

I'm combining 8-bit integers to a 32-bit integer. When the first byte is 0, python for some reason interprets it as a negative number.

a = 0
b = -35
c = 64
d = 0
res = (a << 24) | (b << 16) | c << 8 | d   # res = -2277376 instead of 14499840

I need res to be 14499840 and not -2277376. Any way I can force python not to ignore the first 8 bits?

1 Answers

It's not because of a being zero, but it's because b is negative:

>>> res = (a << 24) | (b << 16) | c << 8 | d
>>> res
-2277376
>>> b << 16
-2293760

So if the bytes can be negative you need to make them positive first by masking with 0xFF:

res = ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | (d & 0xFF)

Or better read the input as unsigned bytes instead of signed

Related