Home >Backend Development >Golang >How to Handle Hexadecimal Strings Larger Than Go's Built-in Integer Types?
Converting hexadecimal strings into decimal numbers can be a challenge when dealing with numbers that exceed the capacity of built-in integer types. Golang provides a powerful solution with its math/big package.
To convert a hexadecimal string into a big.Int, use the SetIntString method.
package main import "math/big" func main() { // Example hexadecimal string hexString := "0x00000000000000000000000000000000000000000000d3c21bcecceda1000000" // Create a new big.Int i := new(big.Int) // Convert the hexadecimal string to a big.Int i.SetString(hexString, 16) // Print the converted number println(i) }
After converting the hexadecimal string to a big.Int, you can truncate the decimal representation by using the Truncate method. For example:
func Truncate(x *big.Int, prec uint) { f := new(big.Float).SetInt(x) f.SetPrec(int64(prec)) f.Int(x) }
This function sets the precision of the big.Float to the desired number of decimal places before converting it back to a big.Int.
You can use the fmt package to parse and format big.Int values:
package main import "fmt" func main() { hexString := "0x000000d3c21bcecceda1000000" // Create a new big.Int i := new(big.Int) // Parse the hexadecimal string fmt.Sscan(hexString, i) // Alternatively, you can use fmt.Sscanf // fmt.Sscanf(hexString, "0x%x", i) // Truncate to 18 decimal places Truncate(i, 18) // Marshal to JSON jsonBytes, _ := i.MarshalJSON() fmt.Println(string(jsonBytes)) }
The above is the detailed content of How to Handle Hexadecimal Strings Larger Than Go's Built-in Integer Types?. For more information, please follow other related articles on the PHP Chinese website!