2008-02-27

fun with masking and shifts


def chunkit(num):
    """
    retun list of 2 byte numbers
    0x12345678 = 0x78, 0x56, 0x34, 0x12
    """
    a = (num & 0xff000000) >> 24
    b = (num & 0x00ff0000) >> 16
    c = (num & 0x0000ff00) >> 8
    d = (num & 0x000000ff)
    return [d,c,b,a]

1 comment:

Unknown said...

That is not a good way to do it, because the shifting operation in most cases is an arithmetic shift, aka the most significant bit will be duplicated down for each shift operation.

Instead use:

a = (b >> 24) & 0xff;