HexToBytes
Converts a hexadecimal string to a byte slice.
Function Signature
func HexToBytes(hexString string) ([]byte, error)Source: keccak.go
Parameters
hexString- The hexadecimal string to be converted (with or without "0x" prefix)
Returns
[]byte- The converted byte sliceerror- An error if the hex string is invalid
Usage Example
package main
import (
"fmt"
"github.com/NethermindEth/starknet.go/utils"
)
func main() {
// Convert hex string to bytes
hexStr := "0x48656c6c6f20576f726c64"
bytes, err := utils.HexToBytes(hexStr)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Hex: %s\n", hexStr)
fmt.Printf("Bytes: %v\n", bytes)
fmt.Printf("String: %s\n", string(bytes))
// Output:
// Hex: 0x48656c6c6f20576f726c64
// Bytes: [72 101 108 108 111 32 87 111 114 108 100]
// String: Hello World
}Error Handling
// Invalid hex string
invalidHex := "0xGGHH"
_, err := utils.HexToBytes(invalidHex)
if err != nil {
fmt.Printf("Invalid hex string: %v\n", err)
}Common Use Cases
- Converting hex address strings to bytes for hashing.
- Decoding hex-encoded calldata or signatures.
- Converting hex hashes to bytes for verification.
- Decoding hex-encoded network data.
See Also
- Type Conversions for working with byte arrays and hex

