def readInteger(s: BinaryIO) -> int: """ Unpack a BER integer :param s: stream """ if not readUniversalTag(s, Tag.BER_TAG_INTEGER, False): raise ValueError("Bad integer tag") size = readLength(s) if size == 1: return Uint8.unpack(s.read(1)) elif size == 2: return Uint16BE.unpack(s.read(2)) elif size == 3: integer1 = Uint8.unpack(s.read(1)) integer2 = Uint16BE.unpack(s.read(2)) return (integer1 << 16) + integer2 elif size == 4: return Uint32BE.unpack(s.read(4)) else: raise ValueError("Wrong integer size")
def readInteger(s: BinaryIO) -> int: """ Unpack a PER integer :param s: stream @raise InvalidValue: if the size of the integer is invalid """ size = readLength(s) if size == 1: return Uint8.unpack(s.read(1)) elif size == 2: return Uint16BE.unpack(s.read(2)) elif size == 4: return Uint32BE.unpack(s.read(4)) else: raise ValueError("invalid integer size %d" % size)
def readLength(s: BinaryIO) -> int: """ Read length of BER structure Length is on 1, 2 or 3 bytes :param s: stream """ byte = Uint8.unpack(s.read(1)) if byte & 0x80: byte &= ~0x80 if byte == 1: return Uint8.unpack(s.read(1)) elif byte == 2: return Uint16BE.unpack(s.read(2)) else: raise ValueError("BER length must be 1 or 2") else: return byte