golang math/big 和 string bytes相互转化

显式初始化

num := big.NewInt(math.MaxInt64)
math.MaxInt64是最大的整数
num := big.NewInt(1999)
fmt.Printf("Big int: %v\n", num)

⚠️显式初始化最大只能是math.MaxInt64,如果还想大,就得需要byte或者string

byte array -> big.Int

import "math/big"

z := new(big.Int)
z.SetBytes(byteSliceHere)

or

func Base64ToInt(s string) (*big.Int, error) {
    data, err := base64.StdEncoding.DecodeString(s)
    if err != nil {
        return nil, err
    }
    i := new(big.Int)
    i.SetBytes(data)
    return i, nil
}

string -> big.Int

package main

import (
    "fmt"
    "math/big"
)

func main() {
    n := new(big.Int)
    n, ok := n.SetString("1234567890987", 10)
    if !ok {
        fmt.Println("SetString: error")
        return
    }
    fmt.Println(n)
}

big.Int > string

bigint := big.NewInt(123)
bigstr := bigint.String()

你可能感兴趣的:(golang math/big 和 string bytes相互转化)