toHex
Encodes a value (string, number, boolean, or byte array) to a hex string
toHex
Encodes a value (string, number, boolean, or byte array) to a hex string with 0x prefix.
Import
import "github.com/ChefBingbong/viem-go/utils/encoding"Usage
import "github.com/ChefBingbong/viem-go/utils/encoding"import "math/big"
// Convert number to hexhex, _ := encoding.ToHex(420).Hex()// "0x1a4"
// Convert string to hexhex, _ := encoding.ToHex("Hello world").Hex()// "0x48656c6c6f20776f726c642e"
// Convert bytes to hexhex, _ := encoding.ToHex([]byte{72, 101, 108, 108, 111}).Hex()// "0x48656c6c6f"
// Convert boolean to hexhex, _ := encoding.ToHex(true).Hex()// "0x1"
// Convert with size paddinghex, _ := encoding.ToHex(420).WithSize(32).Hex()// "0x00000000000000000000000000000000000000000000000000000000000001a4"
// Convert big.Inthex, _ := encoding.ToHex(big.NewInt(420)).Hex()// "0x1a4"Returns
- Type:
(string, error)
The hex-encoded value with 0x prefix.
Parameters
value (required)
- Type:
any(supports[]byte,string,bool,int,int8-64,uint,uint8-64,*big.Int)
The value to encode as hex.
hex, _ := encoding.ToHex(420).Hex()// "0x1a4"
hex, _ := encoding.ToHex("Hello world").Hex()// "0x48656c6c6f20776f726c642e"WithSize(size) (optional)
- Type:
int
Pads the output to the specified byte size.
hex, _ := encoding.ToHex(420).WithSize(32).Hex()// "0x00000000000000000000000000000000000000000000000000000000000001a4"
hex, _ := encoding.ToHex([]byte{0x01}).WithSize(4).Hex()// "0x00000001"WithSigned() (optional)
- Type: method
Treats numbers as signed for conversion (uses two's complement). Requires WithSize to be set.
import "math/big"
// Convert negative number with two's complementhex, _ := encoding.ToHex(big.NewInt(-1)).WithSize(32).WithSigned().Hex()// "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"Standalone Functions
NumberToHex
Converts a number to hex:
hex := encoding.NumberToHex(big.NewInt(420))
// "0x1a4"
StringToHex
Converts a UTF-8 string to hex:
hex := encoding.StringToHex("Hello world")
// "0x48656c6c6f20776f726c642e"
BoolToHex
Converts a boolean to hex:
hex := encoding.BoolToHex(true)
// "0x1"
hex = encoding.BoolToHex(false)
// "0x0"
NumberToHexWithSize
Converts a number to hex with padding:
hex, _ := encoding.NumberToHexWithSize(big.NewInt(420), 32, false)
// "0x00000000000000000000000000000000000000000000000000000000000001a4"