Bkmz

Untitled

Sep 30th, 2011
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3.  
  4. from itertools import izip_longest
  5. import string
  6. from binascii import hexlify
  7. from math import log
  8.  
  9. # global variables
  10.  
  11. # TODO: create dirty hack to work with 3 capacity during specification
  12. capacity = 2
  13.  
  14.  
  15. # end global variables
  16.  
  17. def convert(numb):
  18.     # getting HEX represent, in string, to use it when writing into binary file
  19.     hexNumb = '{0:x}'.format(numb)
  20.     out = ""
  21.    
  22.     # analyze input number, and compute
  23.     if not capacity == 0:
  24.         # checking power of two
  25.         if log(capacity, 2) % 1 == 0.0:
  26.             # we have valid capacity of our integer.
  27.             # now check the max number to given capacity, else raise an Exception
  28.             if numb >= (2**(capacity*8)):
  29.                 raise BaseException("Integer %s not filling in %s bytes capacity, Max INT: %s" %
  30.                                                             (numb, capacity, 2**(capacity*8)))
  31.            
  32.             # starting pushing to output
  33.             for i in _grouper(2, hexNumb.zfill(capacity), 0):
  34.                 # performing modification of izip_longest to string
  35.                 i = string.join(i, "")
  36.                 out += chr(int(i, 16))
  37.                 # using statement below when i want a generator
  38.                 # yield chr(int(i, 16))
  39.            
  40.     return out
  41.        
  42. def unconvert(numb):
  43.     return int(hexlify(numb), 16)
  44.  
  45. fd = open("bin", "wb")
  46.  
  47. def _grouper(n, iterable, fillvalue=None):
  48.     "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
  49.     args = [iter(iterable)] * n
  50.     return izip_longest(fillvalue=fillvalue, *args)
  51.  
  52. def convert2bin(intStr):
  53.     return '{0:x}'.format( intStr )
  54.  
  55.  
  56. def comment():
  57.     num = 3405848999
  58.    
  59.     print convert2bin(num).zfill(8)
  60.    
  61.     for i in _grouper(2, convert2bin(num).zfill(8), 0):
  62.         i = string.join(i, "")
  63.         print i
  64.         fd.write(chr(int(i, 16)))
  65.    
  66.     fd.close()
  67.    
  68.     fd = open("bin", "rb")
  69.     read = fd.read()
  70.     print read
  71.    
  72.     print int(hexlify(read), 16)
  73.    
  74. if __name__ == "__main__":
  75.     print unconvert(convert(6553))
  76. #    print convert(65536)
  77.    
  78.    
  79.    
  80.    
  81.    
  82.  
Advertisement
Add Comment
Please, Sign In to add comment