Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ''' class_ByteReader.py
- Little-endian systems store the least significant byte in the smallest address
- tested with Python27/34
- '''
- class ByteReader(object):
- '''
- reads bytes from a file
- '''
- def __init__(self, filename):
- self._buffer = list(bytearray(open(filename, 'rb').read()))
- self.pos = 0
- self._eof = EOFError('unexpected end of file')
- def read_byte(self):
- '''
- read one byte
- advances position
- '''
- try:
- byte = self._buffer[self.pos]
- self.pos += 1
- return byte
- except IndexError:
- raise self._eof
- def peek_byte(self):
- '''
- return the next byte in the file (look-ahead)
- '''
- try:
- return self._buffer[self.pos]
- except IndexError:
- raise self._eof
- def peek_list(self, n):
- '''
- return a list of the next n bytes
- '''
- return self._buffer[self.pos:self.pos+n]
- def read_short(self):
- '''
- read short (2 bytes little endian)
- '''
- a, b = self.read_list(2)
- # same as a * 256 + b
- return a << 8 | b
- def read_long(self):
- '''
- read long (4 bytes little endian)
- '''
- a, b, c, d = self.read_list(4)
- return a << 24 | b << 16 | c << 8 | d
- def read_list(self, n):
- '''
- read n bytes and return as a list
- advances position
- '''
- i = self.pos
- ret = self._buffer[i:i + n]
- if len(ret) < n:
- raise self._eof
- self.pos += n
- return ret
- def __enter__(self):
- return self
- def __exit__(self, type, value, traceback):
- return False
- # testing the module ...
- if __name__ == '__main__':
- # pick a file you have in the working directory or give full path
- fname = "Farm.gif"
- br = ByteReader(fname)
- print("read first byte = {}".format(br.read_byte()))
- print("peek next 10 bytes = {}".format(br.peek_list(10)))
- print("take 2 bytes:")
- print(br.peek_list(2))
- print("calculate a two byte value (little endian):")
- two_bytes = br.peek_list(2)
- print(two_bytes[0]*256 + two_bytes[1])
- # same result
- print(br.read_short())
- print("take 4 bytes:")
- print(br.peek_list(4))
- print("calculate value (4 bytes little endian):")
- print(br.read_long())
- print("read next 8 bytes:")
- print(br.read_list(8))
Advertisement
Add Comment
Please, Sign In to add comment