Conversion Functions
Utility functions for converting between different data types commonly used in Starknet development.
Common Conversion Patterns
Understanding when and how to use conversions is key to working efficiently with Starknet data types.
Conversion Flow Diagram
┌─────────────┐ ┌──────────┐ ┌──────────┐
│ Hex String │ ←→ │ Felt │ ←→ │ BigInt │
└─────────────┘ └──────────┘ └──────────┘
↓ ↓ ↓
┌─────────────┐ ┌──────────┐ ┌──────────┐
│ Hex Array │ ←→ │ Felt[] │ ←→ │BigInt[] │
└─────────────┘ └──────────┘ └──────────┘
↓
┌─────────────┐
│ Bytes │ ←→ BigInt
└─────────────┘Pattern 1: Working with Contract Addresses
// String → Felt (most common for addresses)
addressStr := "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7"
address, err := utils.HexToFelt(addressStr)
// Use in RPC calls
balance, err := client.Call(ctx, rpc.FunctionCall{
ContractAddress: address,
// ...
})Pattern 2: Mathematical Operations on Felt Values
// Felt → BigInt → Math → Felt
contractValue, _ := client.Call(ctx, call) // Returns felt
bigValue := utils.FeltToBigInt(contractValue)
// Perform operations
doubled := new(big.Int).Mul(bigValue, big.NewInt(2))
halved := new(big.Int).Div(bigValue, big.NewInt(2))
// Convert back to felt for Starknet
resultFelt := utils.BigIntToFelt(doubled)Pattern 3: Building Transaction Calldata
// Multiple hex values → Felt array (common for calldata)
calldata := []string{
"0x1", // Number of calls
"0x049d...", // Contract address
"0x83afd3f4caedc6eeb...", // Function selector
"0x0", // Data offset
"0x2", // Data length
"0x1234", // First parameter
"0x5678", // Second parameter
}
calldataFelts, err := utils.HexArrToFelt(calldata)
if err != nil {
log.Fatal(err)
}
// Use in transaction
tx := rpc.InvokeTxnV3{
Calldata: calldataFelts,
// ...
}Pattern 4: Parsing Contract Output
// Contract returns felt array, need to convert to readable format
output := []*felt.Felt{...} // From contract call
// Convert to big integers for processing
bigInts := make([]*big.Int, len(output))
for i, felt := range output {
bigInts[i] = utils.FeltToBigInt(felt)
}
// Or convert to hex strings for display
hexStrings := make([]string, len(output))
for i, felt := range output {
bigInt := utils.FeltToBigInt(felt)
hexStrings[i] = utils.BigToHex(bigInt)
}Pattern 5: Working with Short Strings
// Hex → Short string (for Cairo short strings)
nameHex := "0x537461726b6e6574" // "Starknet" in hex
name := utils.HexToShortStr(nameHex)
fmt.Println(name) // Output: "Starknet"
// String → Hex (for encoding short strings)
text := "Hello"
hexText := utils.StrToHex(text)Choosing the Right Conversion
| From | To | Function | When to Use |
|---|---|---|---|
| Hex String | Felt | HexToFelt | Contract addresses, transaction hashes, class hashes |
| Hex Array | Felt Array | HexArrToFelt | Building calldata from string values |
| Felt | BigInt | FeltToBigInt | Math operations, comparisons, working with other Go libraries |
| BigInt | Felt | BigIntToFelt | Preparing results for Starknet calls |
| Hex | BigInt | HexToBN | Quick hex parsing without intermediate felt |
| BigInt | Hex | BigToHex | Display, logging, debugging |
| Hex | Short String | HexToShortStr | Reading Cairo short strings |
| String | Hex | StrToHex | Encoding short strings for Cairo |
| Hex | Bytes | HexToBytes | Low-level operations, hashing |
| Bytes | BigInt | BytesToBig | Processing raw byte data |
| Uint64 | Felt | Uint64ToFelt | Converting Go integers to Starknet values |
Performance Tips
Avoid Unnecessary Conversions:// ❌ BAD: Multiple conversions
hex := "0x123"
felt, _ := utils.HexToFelt(hex)
bigInt := utils.FeltToBigInt(felt)
result := utils.BigToHex(bigInt)
// ✅ GOOD: Direct conversion when possible
bigInt, _ := utils.HexToBN("0x123")
result := utils.BigToHex(bigInt)// ✅ Convert arrays at once rather than in a loop
hexValues := []string{"0x1", "0x2", "0x3"}
felts, err := utils.HexArrToFelt(hexValues) // Single call
// ❌ Avoid converting one at a time if you have many values
for _, hex := range hexValues {
felt, _ := utils.HexToFelt(hex) // Multiple calls
}Error Handling Best Practices
// Always check conversion errors
address, err := utils.HexToFelt(addressStr)
if err != nil {
// Handle invalid hex format
log.Printf("Invalid address format: %v", err)
return err
}
// Validate before conversion
if !strings.HasPrefix(addressStr, "0x") {
return errors.New("address must start with 0x")
}Felt Conversions
HexToFelt
Converts a hexadecimal string to a Felt object.
func HexToFelt(hex string) (*felt.Felt, error)hex- The input hexadecimal string to be converted
*felt.Felt- A pointer to the converted Felt objecterror- Error if conversion fails
package main
import (
"fmt"
"log"
"github.com/NethermindEth/starknet.go/utils"
)
func main() {
// Convert hex string to felt
address, err := utils.HexToFelt("0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7")
if err != nil {
log.Fatal("Conversion failed:", err)
}
fmt.Printf("Felt: %s\n", address)
}HexArrToFelt
Converts an array of hexadecimal strings to an array of Felt objects.
func HexArrToFelt(hexArr []string) ([]*felt.Felt, error)hexArr- An array of strings representing hexadecimal values
[]*felt.Felt- An array of Felt objectserror- Error if any conversion fails
hexStrings := []string{
"0x1",
"0x2",
"0x3",
}
felts, err := utils.HexArrToFelt(hexStrings)
if err != nil {
log.Fatal("Conversion failed:", err)
}
fmt.Printf("Converted %d felts\n", len(felts))FeltArrToStringArr
Converts an array of Felt objects to an array of string objects.
func FeltArrToStringArr(f []*felt.Felt) []stringf- The array of Felt objects to convert
[]string- The array of string objects
felts := []*felt.Felt{
new(felt.Felt).SetUint64(1),
new(felt.Felt).SetUint64(2),
new(felt.Felt).SetUint64(3),
}
strings := utils.FeltArrToStringArr(felts)
fmt.Printf("Strings: %v\n", strings)Big.Int Conversions
BigIntToFelt
Converts a big integer to a Felt.
func BigIntToFelt(bigNum *big.Int) *felt.FeltbigNum- The big integer to convert
*felt.Felt- The converted Felt value
import "math/big"
bigNum := big.NewInt(12345)
feltNum := utils.BigIntToFelt(bigNum)
fmt.Printf("Felt: %s\n", feltNum)FeltToBigInt
Converts a Felt value to a big.Int.
func FeltToBigInt(f *felt.Felt) *big.Intf- The Felt value to convert
*big.Int- The converted value
felt := new(felt.Felt).SetUint64(12345)
bigNum := utils.FeltToBigInt(felt)
fmt.Printf("Big.Int: %s\n", bigNum.String())BigIntArrToFeltArr
Converts an array of big.Int objects to an array of Felt objects.
func BigIntArrToFeltArr(bigArr []*big.Int) []*felt.FeltbigArr- The array of big.Int objects to convert
[]*felt.Felt- The array of Felt objects
bigInts := []*big.Int{
big.NewInt(1),
big.NewInt(2),
big.NewInt(3),
}
felts := utils.BigIntArrToFeltArr(bigInts)
fmt.Printf("Converted %d felts\n", len(felts))FeltArrToBigIntArr
Converts an array of Felt objects to an array of big.Int objects.
func FeltArrToBigIntArr(f []*felt.Felt) []*big.Intf- The array of Felt objects to convert
[]*big.Int- The array of big.Int objects
felts := []*felt.Felt{
new(felt.Felt).SetUint64(1),
new(felt.Felt).SetUint64(2),
}
bigInts := utils.FeltArrToBigIntArr(felts)
fmt.Printf("Converted %d big.Ints\n", len(bigInts))Hex and Byte Conversions
HexToBN
Converts a hexadecimal string to a big.Int. Automatically trims the "0x" prefix if it exists.
func HexToBN(hexString string) *big.InthexString- The hexadecimal string to be converted
*big.Int- The converted value
bigNum := utils.HexToBN("0x1234")
fmt.Printf("Big.Int: %s\n", bigNum.String())BigToHex
Converts a big integer to its hexadecimal representation.
func BigToHex(in *big.Int) stringin- The big integer to be converted
string- The hexadecimal representation
bigNum := big.NewInt(4660)
hex := utils.BigToHex(bigNum)
fmt.Printf("Hex: %s\n", hex) // Output: 0x1234HexToBytes
Converts a hexadecimal string to a byte slice. Automatically trims the "0x" prefix if it exists.
func HexToBytes(hexString string) ([]byte, error)hexString- The hexadecimal string to be converted
[]byte- The converted byte sliceerror- An error if conversion fails
bytes, err := utils.HexToBytes("0x48656c6c6f")
if err != nil {
log.Fatal("Conversion failed:", err)
}
fmt.Printf("Bytes: %v\n", bytes)BytesToBig
Converts a byte slice to a big.Int.
func BytesToBig(bytes []byte) *big.Intbytes- The byte slice to be converted
*big.Int- The converted value
bytes := []byte{0x12, 0x34}
bigNum := utils.BytesToBig(bytes)
fmt.Printf("Big.Int: %s\n", bigNum.String())String Conversions
StringToByteArrFelt
Converts a string to an array of Felt objects following the Cairo ByteArray format.
The returned array follows the Cairo ByteArray serialization format:
[number of 31-byte felts, 31-byte felts..., pending word (max 30 bytes), pending word byte size]
For more details, see the Starknet documentation on ByteArray serialization.
func StringToByteArrFelt(s string) ([]*felt.Felt, error)s- String/bytearray to convert
[]*felt.Felt- The array of Felt objectserror- An error if any
str := "Hello, Starknet!"
felts, err := utils.StringToByteArrFelt(str)
if err != nil {
log.Fatal("Conversion failed:", err)
}
fmt.Printf("Converted to %d felts\n", len(felts))ByteArrFeltToString
Converts an array of Felts to a string following the Cairo ByteArray format.
The input array should follow the Cairo ByteArray serialization format:
[number of 31-byte felts, 31-byte felts..., pending word (max 30 bytes), pending word byte size]
For more details, see the Starknet documentation on ByteArray serialization.
func ByteArrFeltToString(arr []*felt.Felt) (string, error)arr- The array of Felt objects
string- The converted stringerror- An error if any
// Assuming 'felts' is a ByteArray format felt array
str, err := utils.ByteArrFeltToString(felts)
if err != nil {
log.Fatal("Conversion failed:", err)
}
fmt.Printf("String: %s\n", str)HexToShortStr
Converts a hexadecimal string to a short string (Cairo short string representation).
func HexToShortStr(hexStr string) stringhexStr- The hexadecimal string to convert
string- A short string
// 0x455448 represents "ETH" in hex
shortStr := utils.HexToShortStr("0x455448")
fmt.Printf("Short string: %s\n", shortStr) // Output: ETHNumeric Conversions
Uint64ToFelt
Generates a new Felt from a given uint64 number.
func Uint64ToFelt(num uint64) *felt.Feltnum- The uint64 number to convert to a Felt
*felt.Felt- A Felt representation of the number
felt := utils.Uint64ToFelt(12345)
fmt.Printf("Felt: %s\n", felt)U256 Conversions
HexToU256Felt
Converts a hexadecimal string to a Cairo u256 representation.
The Cairo u256 is represented as two Felt values:
- The first Felt contains the 128 least significant bits (low part)
- The second Felt contains the 128 most significant bits (high part)
func HexToU256Felt(hexStr string) ([]*felt.Felt, error)hexStr- The hexadecimal string to convert to a Cairo u256
[]*felt.Felt- A slice containing two Felt values [low, high]error- Error if conversion fails
// Convert a large hex value to u256
u256, err := utils.HexToU256Felt("0x123456789abcdef0123456789abcdef0")
if err != nil {
log.Fatal("Conversion failed:", err)
}
fmt.Printf("U256 low: %s, high: %s\n", u256[0], u256[1])U256FeltToHex
Converts a Cairo u256 representation (two Felt values) back to a hexadecimal string.
The Cairo u256 is represented as two Felt values:
- The first Felt contains the 128 least significant bits (low part)
- The second Felt contains the 128 most significant bits (high part)
func U256FeltToHex(u256 []*felt.Felt) (string, error)u256- A slice containing two Felt values [low, high]
string- The hexadecimal representation of the combined valueerror- Error if conversion fails
// Convert u256 back to hex
low := new(felt.Felt).SetUint64(0x123456789abcdef0)
high := new(felt.Felt).SetUint64(0x123456789abcdef0)
u256 := []*felt.Felt{low, high}
hex, err := utils.U256FeltToHex(u256)
if err != nil {
log.Fatal("Conversion failed:", err)
}
fmt.Printf("Hex: %s\n", hex)Related
- Cryptographic Utilities - Cryptographic and hashing functions
- Unit Conversions - Currency and unit conversions
- Types - Type definitions

