diff python/ppci/core/bitreader.py @ 104:ed230e947dc6

Added hexviewer
author windel
date Sun, 30 Dec 2012 22:31:55 +0100
parents 4a37d6992bd3
children 6a303f835c6d
line wrap: on
line diff
--- a/python/ppci/core/bitreader.py	Wed Dec 26 10:53:33 2012 +0100
+++ b/python/ppci/core/bitreader.py	Sun Dec 30 22:31:55 2012 +0100
@@ -26,3 +26,49 @@
          return int(b[0])
       return 2
 
+class BitstreamWriter:
+   def __init__(self, f):
+      self.f = f
+      self.u32 = 0
+      self.curpos = 0
+   def Emit1(self, val):
+      self.Emit(val, 1)
+   def Emit(self, val, numbits):
+      """ Emits value using numbits bits """
+      if numbits == 1:
+         if val != 0:
+            self.u32 |= (0x1 << self.curpos)
+         self.curpos += 1
+         if self.curpos == 32:
+            self.writeWord()
+      elif numbits > 1:
+         for i in range(numbits):
+            if val & (1 << i) != 0:
+               self.Emit1(1)
+            else:
+               self.Emit1(0)
+   def writeWord(self):
+      bts = struct.pack('<I', self.u32)
+      self.f.write(bts)
+      self.u32 = 0
+      self.curpos = 0
+   def flush(self):
+      if self.curpos != 0:
+         self.writeWord()
+
+class BitcodeWriter:
+   def __init__(self):
+      pass
+   def WriteModule(self, module):
+      pass
+   def WriteModuleToFile(self, module, f):
+      s = BitstreamWriter(f)
+      s.Emit(ord('B'), 8)
+      s.Emit(ord('C'), 8)
+      s.Emit(0x0, 4)
+      s.Emit(0xC, 4)
+      s.Emit(0xE, 4)
+      s.Emit(0xD, 4)
+      self.WriteModule(module)
+      s.flush()
+