fromHex
Decodes a hex string to bytes, number, boolean, or string
Loading...
Decodes a hex string to bytes, number, boolean, or string
Decodes a hex string to bytes, number, boolean, or string using a fluent API.
import "github.com/ChefBingbong/viem-go/utils/encoding"import "github.com/ChefBingbong/viem-go/utils/encoding"import "math/big"
// Convert hex to bytesbytes, _ := encoding.FromHex("0x48656c6c6f").ToBytes()// []byte{72, 101, 108, 108, 111}
// Convert hex to big.Intnum, _ := encoding.FromHex("0x1a4").ToBigInt()// big.Int representing 420
// Convert hex to int64num, _ := encoding.FromHex("0x1a4").ToNumber()// int64(420)
// Convert hex to uint64num, _ := encoding.FromHex("0x1a4").ToUint()// uint64(420)
// Convert hex to booleanb, _ := encoding.FromHex("0x1").ToBool()// true
// Convert hex to stringstr, _ := encoding.FromHex("0x48656c6c6f20776f726c642e").ToString()// "Hello world."
// With size validationbytes, _ := encoding.FromHex("0x01").WithSize(4).ToBytes()// []byte{0x00, 0x00, 0x00, 0x01} (padded)[]byte, *big.Int, int64, uint64, bool, string, error)The decoded value in the requested format.
stringThe hex string to decode (should have 0x prefix).
bytes, _ := encoding.FromHex("0x48656c6c6f").ToBytes()intValidates and optionally pads the hex to the specified byte size.
// Validate size and pad if neededbytes, _ := encoding.FromHex("0x01").WithSize(4).ToBytes()// []byte{0x00, 0x00, 0x00, 0x01}Treats the hex as a signed integer (two's complement) for ToBigInt and ToNumber conversions.
// Convert signed hexnum, _ := encoding.FromHex("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"). WithSize(32). WithSigned(). ToBigInt()// big.Int representing -1Converts hex to a byte slice:
bytes, _ := encoding.FromHex("0x0102").ToBytes()
// []byte{0x01, 0x02}
Converts hex to a *big.Int:
num, _ := encoding.FromHex("0x1a4").ToBigInt()
// big.Int representing 420
Converts hex to an int64:
num, _ := encoding.FromHex("0x1a4").ToNumber()
// int64(420)
Converts hex to a uint64:
num, _ := encoding.FromHex("0x1a4").ToUint()
// uint64(420)
Converts hex to a boolean:
b, _ := encoding.FromHex("0x1").ToBool()
// true
b, _ = encoding.FromHex("0x0").ToBool()
// false
Converts hex to a UTF-8 string:
str, _ := encoding.FromHex("0x48656c6c6f").ToString()
// "Hello"
Converts hex to bytes:
bytes, _ := encoding.HexToBytes("0x0102")
// []byte{0x01, 0x02}
Converts hex to *big.Int:
num, _ := encoding.HexToBigInt("0x1a4", false)
// big.Int representing 420
Converts hex to int64:
num, _ := encoding.HexToNumber("0x1a4", false)
// int64(420)
Converts hex to uint64:
num, _ := encoding.HexToUint("0x1a4")
// uint64(420)
Converts hex to boolean:
b, _ := encoding.HexToBool("0x1")
// true
Converts hex to string:
str, _ := encoding.HexToString("0x48656c6c6f")
// "Hello"