-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompress.py
More file actions
65 lines (51 loc) · 1.58 KB
/
compress.py
File metadata and controls
65 lines (51 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import utils
import pathlib
import sys
def compress():
name = ''
raw = ''
try:
name = sys.argv[1]
raw = open(name, "rb")
except IndexError:
print("Choose file you want to compress")
exit()
if pathlib.Path(name).suffix == ".hfcd":
print("File compressed")
exit()
content = raw.read()
counter = {}
for item in content:
letter = item.to_bytes(1, byteorder="big")
if counter.get(letter) is None:
counter[letter] = 1
else:
counter[letter] += 1
node = utils.get_tree(counter)
codes = node.get_dict()
print(codes)
print(counter)
raw_size = len(content) * 8
compressed_size = 0
for key in codes:
compressed_size += len(codes[key]) * counter[key]
print(f"raw: {raw_size} compressed without header: {compressed_size}")
empty_bits = (8 - compressed_size % 8) % 8
print(empty_bits)
utils.print_hashsum(content)
output = open(f"{pathlib.Path(name)}.hfcd", "wb")
output.write(empty_bits.to_bytes(1, byteorder="big"))
output.write((len(counter) % 256).to_bytes(1, byteorder="big"))
for key in counter:
output.write(key)
output.write(counter[key].to_bytes(4, byteorder="big"))
buffer = "0" * empty_bits
for letter in content:
buffer += codes[letter.to_bytes(1, byteorder="big")]
while len(buffer) >= 8:
output.write(int(buffer[7::-1], 2).to_bytes(1, byteorder='big'))
buffer = buffer[8:]
raw.close()
output.close()
if __name__ == '__main__':
compress()