A Python port of the Invisible Internet Project (I2P)
at main 32 lines 974 B view raw
1"""HexDump — hex encoding/decoding utilities. 2 3Ported from net.i2p.util.HexDump. 4""" 5 6 7class HexDump: 8 """Hex dump formatting similar to `hexdump -C`.""" 9 10 @staticmethod 11 def dump(data: bytes, offset: int = 0, length: int = -1) -> str: 12 if length < 0: 13 length = len(data) - offset 14 lines = [] 15 for i in range(0, length, 16): 16 chunk = data[offset + i : offset + min(i + 16, length)] 17 hex_part = " ".join(f"{b:02x}" for b in chunk) 18 ascii_part = "".join( 19 chr(b) if 32 <= b < 127 else "." for b in chunk 20 ) 21 lines.append(f"{i:08x} {hex_part:<48s} |{ascii_part}|") 22 return "\n".join(lines) 23 24 @staticmethod 25 def to_hex(data: bytes) -> str: 26 """Convert bytes to hex string.""" 27 return data.hex() 28 29 @staticmethod 30 def from_hex(hex_str: str) -> bytes: 31 """Convert hex string to bytes.""" 32 return bytes.fromhex(hex_str)