Skip to content

Instantly share code, notes, and snippets.

@PyYoshi
Created August 10, 2012 08:43
Show Gist options
  • Select an option

  • Save PyYoshi/3312654 to your computer and use it in GitHub Desktop.

Select an option

Save PyYoshi/3312654 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import struct
class BinaryReader:
# based: http://code.activestate.com/recipes/577610-decoding-binary-files/
# http://www.python.jp/doc/nightly/library/struct.html
_TYPES = {
'int8' : struct.Struct('<b'),
'uint8' : struct.Struct('<B'),
'int16' : struct.Struct('<h'),
'uint16' : struct.Struct('<H'),
'int32' : struct.Struct('<i'),
'uint32' : struct.Struct('<I'),
'int64' : struct.Struct('<q'),
'uint64' : struct.Struct('<Q'),
'float' : struct.Struct('<f'),
'float32' : struct.Struct('<f'),
'single' : struct.Struct('<f'),
'float64' : struct.Struct('<d'),
'double' : struct.Struct('<d'),
'char' : struct.Struct('<c'),
'char[]' : struct.Struct('<s'),
'pad' : struct.Struct('<x'),
'bool' : struct.Struct('<?'),
}
_FORMATS = {
'int8' : 'b',
'uint8' : 'B',
'int16' : 'h',
'uint16' : 'H',
'int32' : 'i',
'uint32' : 'I',
'int64' : 'q',
'uint64' : 'Q',
'float' : 'f',
'float32' : 'f',
'single' : 'f',
'float64' : 'd',
'double' : 'd',
'char' : 'c',
'char[]' : 's',
'pad' : 'x',
'bool' : '?',
}
def __init__(self, fp):
self.stream = fp.read()
self.index = 0
def read(self,type, next=False):
t = self._TYPES[type]
value = t.unpack_from(self.stream,self.index)[0]
self.index += t.size
if next:
self.next(t.size)
return value
def reads(self,type, next=False):
# return multiple-values
t = self._TYPES[type]
values = t.unpack_from(self.stream,self.index)
self.index += t.size
if next:
self.next(t.size)
return values
def next(self, count):
return self.stream[self.index:self.index+count]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment