Usage

Example HexBytes usage:

>>> from hexbytes import HexBytes

# convert from bytes to a prettier representation at the console
>>> HexBytes(b"\x03\x08wf\xbfh\xe7\x86q\xd1\xeaCj\xe0\x87\xdat\xa1'a\xda\xc0 \x01\x1a\x9e\xdd\xc4\x90\x0b\xf1;")
HexBytes('0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b')

# HexBytes accepts the hex string representation as well, ignoring case and 0x prefixes
>>> hb = HexBytes('03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B')
>>> hb
HexBytes('0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b')
>>> hb = HexBytes('0x03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B')
>>> hb
HexBytes('0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b')

# HexBytes does not override the .hex() or __str__ methods of the parent bytes type
>>> hb = HexBytes('03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B')
>>> hb.hex()
'03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b'
>>> print(hb)
b"\x03\x08wf\xbfh\xe7\x86q\xd1\xeaCj\xe0\x87\xdat\xa1'a\xda\xc0 \x01\x1a\x9e\xdd\xc4\x90\x0b\xf1;"

# Use the to_0x_hex method to get a 0x-prefixed hex string
>>> hb.to_0x_hex()
'0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b'


# get the first byte:
>>> hb[0]
3

# get the first 5 bytes:
>>> hb[:5]
HexBytes('0x03087766bf')

# show how many bytes are in the value
>>> len(hb)
32

# cast back to the basic bytes type
>>> bytes(hb)
b"\x03\x08wf\xbfh\xe7\x86q\xd1\xeaCj\xe0\x87\xdat\xa1'a\xda\xc0 \x01\x1a\x9e\xdd\xc4\x90\x0b\xf1;"

HexBytes

class hexbytes.main.HexBytes(val: bool | bytearray | bytes | int | str | memoryview)

Bases: bytes

Thin wrapper around the python built-in bytes class.

It has these changes:
  1. Accepts more initializing values: bool, bytearray, bytes, (non-negative) int, str, and memoryview

  2. The representation at console (__repr__) is 0x-prefixed

  3. to_0x_hex returns a 0x-prefixed hex string

to_0x_hex() str

Convert the bytes to a 0x-prefixed hex string