Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # LZcompress
- from os.path import getsize as sz
- import sys
- from math import ceil, log
- # Args
- src, dst = open(sys.argv[1], 'rb'), open(sys.argv[2], 'wb+')
- buff_text = src.read()
- buff_binary = left = ''
- lem = {"0": 0, "1": 1}
- cur_index = 2
- # Gamma
- original_size = sz(sys.argv[1])
- arr = ''.join(["{0:{f}8b}".format(byte, f='0') for byte in buff_text])
- buff_binary += '0'*int(log(original_size, 2)) + \
- "{0:{f}8b}".format(original_size, f='0')
- # Write to buffer
- for bit in arr:
- if (left+bit) not in lem:
- inbin = "{0:b}".format(lem[left])
- buff_binary += (ceil(log(cur_index, 2)) - len(inbin)) * '0' + inbin
- lem[left + '0'], lem[left + '1'] = lem[left], cur_index
- cur_index += 1
- left = bit
- else:
- left += bit
- # Padding
- while left not in lem:
- left += '0'
- inbin = "{0:b}".format(lem[left])
- buff_binary += (ceil(log(cur_index, 2)) - len(inbin)) * '0' + inbin
- buff_binary += '1{}'.format('0' * (7 - len(buff_binary) % 8))
- # Write to file
- for i in range(int(len(buff_binary) / 8)):
- num = int(buff_binary[i * 8:(i + 1) * 8], 2)
- dst.write(num.to_bytes(1, byteorder='big'))
- # LZDecompress
- from math import ceil, log
- import os
- import sys
- sf, df = open(sys.argv[1], 'rb'), open(sys.argv[2], 'wb+')
- lem = {0: "0", 1: "1"}
- ind = 2
- # read Gamma code
- buf = sf.read(4096)
- BUFTOREAD = ''.join(["{0:{f}8b}".format(byte, f='0') for byte in buf])
- index = BUFTOREAD.index('1')
- file_size = int('1{}'.format(''.join(BUFTOREAD[index + 1:2 * index + 1])), 2)
- # Read Lempel-Ziv coding
- BUFTOWRITE, BUFTOREAD = '', BUFTOREAD[2 * index + 1:]
- while True:
- while ceil(log(len(lem), 2)) <= len(BUFTOREAD):
- i = int(BUFTOREAD[:ceil(log(len(lem), 2))], 2)
- BUFTOWRITE += lem[i]
- BUFTOREAD = BUFTOREAD[ceil(log(len(lem), 2)):]
- lem[ind], lem[i] = lem[i] + '1', lem[i] + '0'
- ind += 1
- buf = sf.read(4096)
- if not buf:
- break
- BUFTOREAD += ''.join(["{0:{f}8b}".format(byte, f='0') for byte in buf])
- # Write to file
- for i in range(int(len(BUFTOWRITE) / 8)):
- if file_size == 0:
- break
- num = int(BUFTOWRITE[i * 8:(i + 1) * 8], 2)
- df.write(num.to_bytes(1, byteorder='big'))
- file_size -= 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement