arrows-rotatehex_to_bytes

Convert a hex string to raw bytes

Convert a hex string to raw bytes, stripping an optional 0x prefix.

Overview

hex_to_bytes() is a convenience wrapper around bytes.fromhex() that accepts both "0xabcd…" and "abcd…" formats. It handles the common case of hex-encoded data that may or may not include an Ethereum-style 0x prefix.

Signature

def hex_to_bytes(hex_string: str) -> bytes:

Parameters

Parameter
Type
Required
Description

hex_string

str

Yes

Hex-encoded string, with or without a "0x" prefix

Returns

Type
Description

bytes

Decoded raw bytes

Raises

  • ValueError — If hex_string contains non-hex characters or has odd length after prefix removal

Examples

Basic Usage

Load Key from Environment

Validate Hex Input

Notes

  • Equivalent to bytes.fromhex(hex_string.removeprefix("0x"))

  • Does not validate length — use Bytes32 or PrivateKey for length-checked values

  • For loading private keys from hex, prefer PrivateKey.from_hex_str() which combines decoding and validation

See Also

Last updated