Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python2
- # -*- coding: utf-8 -*-
- from itertools import izip_longest
- import string
- from binascii import hexlify
- from math import log
- # global variables
- # TODO: create dirty hack to work with 3 capacity during specification
- capacity = 2
- # end global variables
- def convert(numb):
- # getting HEX represent, in string, to use it when writing into binary file
- hexNumb = '{0:x}'.format(numb)
- out = ""
- # analyze input number, and compute
- if not capacity == 0:
- # checking power of two
- if log(capacity, 2) % 1 == 0.0:
- # we have valid capacity of our integer.
- # now check the max number to given capacity, else raise an Exception
- if numb >= (2**(capacity*8)):
- raise BaseException("Integer %s not filling in %s bytes capacity, Max INT: %s" %
- (numb, capacity, 2**(capacity*8)))
- # starting pushing to output
- for i in _grouper(2, hexNumb.zfill(capacity), 0):
- # performing modification of izip_longest to string
- i = string.join(i, "")
- out += chr(int(i, 16))
- # using statement below when i want a generator
- # yield chr(int(i, 16))
- return out
- def unconvert(numb):
- return int(hexlify(numb), 16)
- fd = open("bin", "wb")
- def _grouper(n, iterable, fillvalue=None):
- "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
- args = [iter(iterable)] * n
- return izip_longest(fillvalue=fillvalue, *args)
- def convert2bin(intStr):
- return '{0:x}'.format( intStr )
- def comment():
- num = 3405848999
- print convert2bin(num).zfill(8)
- for i in _grouper(2, convert2bin(num).zfill(8), 0):
- i = string.join(i, "")
- print i
- fd.write(chr(int(i, 16)))
- fd.close()
- fd = open("bin", "rb")
- read = fd.read()
- print read
- print int(hexlify(read), 16)
- if __name__ == "__main__":
- print unconvert(convert(6553))
- # print convert(65536)
Advertisement
Add Comment
Please, Sign In to add comment