Home >Backend Development >Golang >How to Convert a Big Int to a String or Integer in Go?

How to Convert a Big Int to a String or Integer in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 15:42:11630browse

How to Convert a Big Int to a String or Integer in Go?

Converting a Big Int to String or Integer in Go

When working with large integers in Golang, it may be necessary to convert them to strings or regular integers for display or mathematical operations. The math/big package provides functionality to handle these conversions efficiently.

Converting to a String:

To convert a big int into a string representation, use the String() method provided by the big.Int type:

package main

import (
    "fmt"
    "math/big"
)

func main() {
    bigint := big.NewInt(123)
    bigstr := bigint.String()
    fmt.Println(bigstr) // Output: 123
}

Converting to an Integer:

To convert a big int into an integer (int64), use the Int64() method:

package main

import (
    "fmt"
    "math/big"
)

func main() {
    bigint := big.NewInt(123)
    int64val := bigint.Int64()
    fmt.Println(int64val) // Output: 123
}

Note that the Int64() method only works for big ints that can fit into an int64. For larger integers, use the Bytes() method to get the underlying byte representation and convert it accordingly.

The above is the detailed content of How to Convert a Big Int to a String or Integer in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn