views:

179

answers:

1

Four consecutive bytes in a byte string together specify some value. However, only 7 bits in each byte are used; the most significant bit is always zero and therefore its ignored (that makes 28 bits altogether). So...

b"\x00\x00\x02\x01"

would be 000 0000 000 0000 000 0010 000 0001.

Or, for the sake of legibility, 10 000 0001. That's the value the four bytes represent. But I want a decimal, so I do this:

>>> 0b100000001
257

I can work all that out myself, but how would I incorporate it into a program?

+6  A: 

Use bitshifting and addition:

bytes = b"\x00\x00\x02\x01"
i = 0
for b in bytes:
    i <<= 7
    i += b     # Or use (b & 0x7f) if the last bit might not be zero.
print(i)

Result:

257
Mark Byers
miara
@miara: Thanks, you are right. I was assuming that it was zero.
Mark Byers
Actually it is zero. Your unedited answer was right. I'll edit my question.