It would be neater to use literals instead of calling int
. You can use binary literals or hex, for example:
major = (v & 0xf0) >> 4
minor = (v & 0x0f)
Binary literals only work for Python 2.6 or later and are of the form 0b11110000
. If you are using Python 2.6 or later then you might want to look at the bytearray
type as this will let you treat the data as binary and so not have to use the call to ord
.
If you are parsing binary data and finding that you are having to do lots of bit wise manipulations then you might like to try a more general solution as there are some third-party module that specialise in this. One is hachoir, and a lower level alternative is bitstring (which I wrote). In this your parsing would become something like:
major, minor = data.readlist('uint:4, uint:4')
which can be easier to manage if you're doing a lot of such reads.