Skip to content

Commit

Permalink
Fix Bigint.pack for odd-length hex integers (#58)
Browse files Browse the repository at this point in the history
* Fix Bigint.pack for odd-length hex integers

* Use int.to_bytes() instead of unhex()
  • Loading branch information
yunzheng authored Mar 4, 2021
1 parent 419c4ba commit e2f28b0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
14 changes: 6 additions & 8 deletions malduck/string/bin.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,9 @@ def pack(self, other: int, size: Optional[int] = None) -> bytes:
:type size: bytes, optional
:rtype: bytes
"""
packed = unhex(f"{other:x}")[::-1]
if size:
packed = packed[:size].ljust(size, b"\x00")
return packed
if size is None:
size = (other.bit_length() + 7) // 8
return other.to_bytes(size, byteorder="little")

def unpack_be(self, other: bytes, size: Optional[int] = None) -> int:
"""
Expand Down Expand Up @@ -123,10 +122,9 @@ def pack_be(self, other: int, size: Optional[int] = None) -> bytes:
:type size: bytes, optional
:rtype: bytes
"""
packed = unhex(f"{other:x}")
if size:
packed = packed[:size].rjust(size, b"\x00")
return packed
if size is None:
size = (other.bit_length() + 7) // 8
return other.to_bytes(size, byteorder="big")

def __call__(self, s, bitsize):
warnings.warn(
Expand Down
7 changes: 7 additions & 0 deletions tests/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ def test_bigint():
assert bigint.unpack_be(b"ABCDE", 4) == 0x41424344
assert bigint.pack_be(0x41424344, 8) == b"\x00\x00\x00\x00ABCD"

assert bigint.pack(1) == b"\x01"
assert bigint.pack_be(1) == b"\x01"
assert bigint.pack(1234) == b"\xd2\x04"
assert bigint.pack_be(1234) == b"\x04\xd2"
assert bigint.unpack(b"\xd2\x04") == 1234
assert bigint.unpack_be(b"\x04\xd2") == 1234


def test_pack():
assert pack(
Expand Down

0 comments on commit e2f28b0

Please sign in to comment.