Skip to content

Commit

Permalink
add to_0x_hex method to easily create 0x-prefixed strings
Browse files Browse the repository at this point in the history
  • Loading branch information
pacrob committed Mar 19, 2024
1 parent 9bfdb20 commit 8018c5a
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 1 deletion.
5 changes: 5 additions & 0 deletions docs/hexbytes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ Example :class:`~hexbytes.main.HexBytes` usage:
>>> 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
Expand Down
9 changes: 8 additions & 1 deletion hexbytes/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ class HexBytes(bytes):
1. Accepts more initializing values, like hex strings, non-negative integers,
and booleans
2. The representation at console (__repr__) is 0x-prefixed
"""
3. The to_0x_hex method is added to convert the bytes to a 0x-prefixed hex string
""" # noqa: E501

def __new__(cls: Type[bytes], val: BytesLike) -> "HexBytes":
bytesval = to_bytes(val)
Expand All @@ -51,3 +52,9 @@ def __getitem__( # noqa: F811

def __repr__(self) -> str:
return f"HexBytes({'0x' + self.hex()!r})"

def to_0x_hex(self) -> str:
"""
Convert the bytes to a 0x-prefixed hex string
"""
return "0x" + self.hex()
1 change: 1 addition & 0 deletions newsfragments/43.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add ``to_0x_hex()`` method to provide a quick, explicit way to get an 0x-prefixed string
5 changes: 5 additions & 0 deletions tests/core/test_hexbytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ def test_does_not_break_bytes_hex():
assert hb.hex() == "0f1a"


def test_to_0x_hex():
hb = HexBytes(b"\x0F\x1a")
assert hb.to_0x_hex() == "0x0f1a"


@given(st.binary(), st.integers())
def test_hexbytes_index(primitive, index):
hexbytes = HexBytes(primitive)
Expand Down

0 comments on commit 8018c5a

Please sign in to comment.