Bitwise operators

Dealing with binary files often requires pulling apart or assembling data at the byte level. This is exactly what our _int32_to_bytes() function is doing. We'll take a quick look at it because it shows some features of Python we haven't seen before:

def _int32_to_bytes(i):
"""Convert an integer to four bytes in little-endian format."""
return bytes((i & 0xff,
i >> 8 & 0xff,
i >> 16 & 0xff,
i >> 24 & 0xff))

The function uses the >> (bitwise-shift) and & (bitwise-and) operators to extract individual bytes from the integer value. Note that bitwise-and uses the ampersand symbol to distinguish it from logical-and which is the spelled out word "and". The >> operator shifts the binary representation of the integer right by the specified number of bits. The routine shifts the integer argument one, two, and three bytes to the right before extracting the least significant byte with & after each shift. The four resulting integers are used to construct a tuple which is then passed to the bytes() constructor to produce a four byte sequence.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset