Пример #1
0
    __slots__ = ["maxval", "midval"]

    def __init__(self, underlying, bits):
        Adapter.__init__(self, underlying)
        self.maxval = 1 << bits
        self.midval = self.maxval >> 1

    def encode(self, obj, ctx):
        return obj + self.maxval if obj < 0 else obj

    def decode(self, obj, ctx):
        return obj - self.maxval if obj & self.midval else obj


uint24b = Adapter(Sequence(uint8, uint16b),
                  decode=lambda obj, _: (obj[0] << 16) | obj[1],
                  encode=lambda obj, _: (obj >> 16, obj & 0xffff))
sint24b = TwosComplement(uint24b, 24)
uint24l = Adapter(uint24b,
                  decode=lambda obj, _:
                  ((obj >> 16) & 0xff) | (obj & 0xff00) | ((obj & 0xff) << 16),
                  encode=lambda obj, _:
                  ((obj >> 16) & 0xff) | (obj & 0xff00) | ((obj & 0xff) << 16))
sint24l = TwosComplement(uint24l, 24)


class MaskedInteger(Adapter):
    r"""
    >>> m = MaskedInteger(uint16l,
    ...     bottom4 = (0, 4), 
    ...     upper12 = (4, 12),