toBytes
Encodes a value (string, hex, number, or boolean) to a byte array
Loading...
Encodes a value (string, hex, number, or boolean) to a byte array
Encodes a value (string, hex, number, or boolean) to a byte array using a fluent API.
import "github.com/ChefBingbong/viem-go/utils/encoding"import "github.com/ChefBingbong/viem-go/utils/encoding"import "math/big"
// Convert string to bytesbytes, _ := encoding.ToBytes("Hello world").ToBytes()// []byte{72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100}
// Convert hex to bytesbytes, _ := encoding.ToBytes("0x48656c6c6f").ToBytes()// []byte{72, 101, 108, 108, 111}
// Convert number to bytesbytes, _ := encoding.ToBytes(big.NewInt(420)).ToBytes()// []byte{1, 164}
// Convert boolean to bytesbytes, _ := encoding.ToBytes(true).ToBytes()// []byte{1}([]byte, error)The byte array representation of the value.
any (supports string, []byte, bool, int, int8-64, uint, uint8-64, *big.Int)The value to encode as bytes.
bytes, _ := encoding.ToBytes("Hello world").ToBytes()// []byte{72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100}
bytes, _ = encoding.ToBytes("0x0102").ToBytes()// []byte{0x01, 0x02}intValidates that the result doesn't exceed the specified byte size.
// Validate sizebytes, err := encoding.ToBytes([]byte{0x01, 0x02, 0x03}).WithSize(2).ToBytes()// error: size overflowTreats numbers as signed for conversion (uses two's complement). Requires WithSize to be set.
import "math/big"
// Convert negative number with two's complementbytes, _ := encoding.ToBytes(big.NewInt(-1)).WithSize(32).WithSigned().ToBytes()// []byte{0xff, 0xff, ..., 0xff} (32 bytes)The encoding package also provides standalone conversion functions:
Converts a string to bytes:
bytes := encoding.StringToBytes("Hello")
// []byte{72, 101, 108, 108, 111}
Converts hex to bytes:
bytes, _ := encoding.HexToBytes("0x0102")
// []byte{0x01, 0x02}
Converts a number to bytes:
bytes := encoding.NumberToBytes(big.NewInt(420))
// []byte{1, 164}
Converts a boolean to bytes:
bytes := encoding.BoolToBytes(true)
// []byte{1}