HexBytes: Python `bytes` subclass for hex representation

1.3.1 · active · verified Thu Apr 09

HexBytes is a thin wrapper around the Python built-in `bytes` class (version 1.3.1). It extends `bytes` by accepting a wider range of initialization types including `bool`, `int`, `str`, `bytearray`, and `memoryview`. Key features include a 0x-prefixed console representation (`__repr__`) and a `to_0x_hex()` method for consistent 0x-prefixed hexadecimal string output. The library is actively maintained with regular releases.

Warnings

Install

Imports

Quickstart

Initialize HexBytes from various types and retrieve different representations.

from hexbytes import HexBytes

# Convert from bytes to a prettier representation
hb_from_bytes = HexBytes(b"\x03\x08wf\xbfh\xe7\x86q\xd1\xeaCj\xe0\x87\xdat\xa1'a\xda\xc0 \x01\x1a\x9e\xdd\xc4\x90\x0b\xf1;")
print(f"From bytes: {hb_from_bytes}")

# HexBytes accepts hex string representation (ignoring case and 0x prefixes)
hb_from_hex_str = HexBytes('03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B')
print(f"From hex string: {hb_from_hex_str}")

# Get the 0x-prefixed hex string
hex_string_output = hb_from_hex_str.to_0x_hex()
print(f"Using to_0x_hex(): {hex_string_output}")

# Cast back to basic bytes type
original_bytes = bytes(hb_from_hex_str)
print(f"Cast back to bytes: {original_bytes}")

view raw JSON →