import
struct
class
HuffmanNode:
def
__init__(
self
, value
=
None
):
self
.value
=
value
self
.left
=
None
self
.right
=
None
def
read_qword(
file
, addr):
file
.seek(addr)
dword
=
struct.unpack(
"<Q"
,
file
.read(
8
))[
0
]
return
dword
def
build_huffman_tree(
file
):
root_addr
=
0x1300
root_value
=
read_qword(
file
, root_addr)
root
=
HuffmanNode(root_value)
def
build_tree(node):
if
node.value
=
=
0xFF
:
left_addr
=
read_qword(
file
, node.
id
+
8
)
right_addr
=
read_qword(
file
, node.
id
+
16
)
if
left_addr !
=
0
and
left_addr <
0x1310
:
left_node
=
HuffmanNode()
node.left
=
left_node
left_node.
id
=
left_addr
left_value
=
read_qword(
file
, left_addr)
left_node.value
=
left_value
build_tree(left_node)
if
right_addr !
=
0
and
right_addr <
0x1310
:
right_node
=
HuffmanNode()
node.right
=
right_node
right_node.
id
=
right_addr
right_value
=
read_qword(
file
, right_addr)
right_node.value
=
right_value
build_tree(right_node)
build_tree(root)
return
root
def
read_compressed_data(
file
):
file
.seek(
0x580
)
data
=
file
.read(
0x54A
)
binarystring
=
""
for
c
in
data:
binarystring
+
=
format
(
ord
(c),
"08b"
)
return
binarystring
def
decode_huffman_data(binarystring, root):
current_node
=
root
decoded_data
=
""
for
bit
in
binarystring:
if
bit
=
=
"0"
:
current_node
=
current_node.left
elif
bit
=
=
"1"
:
current_node
=
current_node.right
if
current_node.value
is
not
None
:
decoded_data
+
=
chr
(current_node.value)
current_node
=
root
return
decoded_data
def
main():
with
open
(
"payload.bin"
,
"rb"
) as f:
huffman_tree
=
build_huffman_tree(f)
binarystring
=
read_compressed_data(f)
decoded_data
=
decode_huffman_data(binarystring, huffman_tree)
print
(decoded_data)
if
__name__
=
=
"__main__"
:
main()