hex
Root-level hex conversion utilities
hex
Root-level hex conversion utilities providing a fluent API for converting hex strings to other types.
Import
import "github.com/ChefBingbong/viem-go/utils"
Usage
import "github.com/ChefBingbong/viem-go/utils"// Convert hex to bytesbytes, _ := utils.FromHex("0x0102").ToBytes()// []byte{0x01, 0x02}// Convert hex to int64num, _ := utils.FromHex("0x1a4").ToInt()// int64(420)// Convert hex to uint64num, _ := utils.FromHex("0x1a4").ToUint()// uint64(420)// Convert hex to big.IntbigNum, _ := utils.FromHex("0x1a4").ToBigInt()// big.Int representing 420// Convert hex to booleanb, _ := utils.FromHex("0x1").ToBool()// true
Fluent API
FromHex
Creates a HexConverter from a hex string:
converter := utils.FromHex("0x0102")
HexConverter Methods
- ToBytes(): Converts hex to bytes
- ToInt(): Converts hex to int64
- ToUint(): Converts hex to uint64
- ToBigInt(): Converts hex to *big.Int
- ToBool(): Converts hex to boolean
- String(): Returns the original hex string
Standalone Functions
HexToBytes
Converts hex to bytes:
bytes, _ := utils.HexToBytes("0x0102")
HexToInt
Converts hex to int64:
num, _ := utils.HexToInt("0x1a4")
HexToUint
Converts hex to uint64:
num, _ := utils.HexToUint("0x1a4")
HexToBigInt
Converts hex to *big.Int:
bigNum, _ := utils.HexToBigInt("0x1a4")
HexToBool
Converts hex to boolean:
b, _ := utils.HexToBool("0x1")
IsValidHex
Checks if a string is valid hex:
valid := utils.IsValidHex("0x0102")
PadHex
Pads a hex string to a target byte length:
padded := utils.PadHex("0x01", 4)
// "0x00000001"
Notes
- These are root-level utilities in the
utilspackage - For more advanced features (size validation, signed conversions), use the
encodingpackage utilities - The fluent API provides a convenient way to chain conversions