June 2017
Beginner
352 pages
8h 39m
English
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 ...
Read now
Unlock full access