Search code examples
gobigint

How can I preserve big.Int.Bytes() len?


Given:

arr := make([]byte, 8)

fmt.Println(arr) // [0 0 0 0 0 0 0 0]

big := new(big.Int).SetBytes(arr).Bytes()

fmt.Println(big) // []

I tried to put number 1 in and got such results:

... // [0 0 0 0 0 0 0 1] from []byte

...// [1] from big.Int

I have to preserve the length of 8 but big.Int doesn't allow it. How to be able to preserve it still?


Solution

  • The Int type internally does not preserve the bytes from which it was constructed, and Bytes returns the minimum number of bytes that are required to represent the value.

    In order to turn it into a byte slice of a fixed length, use the FillBytes method. You need to ensure that the value fits in the provided byte slice, otherwise it will panic.

    Example:

    package main
    
    import (
        "fmt"
        "math/big"
    )
    
    func main() {
        xarr := []byte{1, 2, 3}
        fmt.Println(xarr)
    
        x := new(big.Int).SetBytes(xarr)
        fmt.Println(x)
    
        y := big.NewInt(0)
        y.Add(x, big.NewInt(2560))
        fmt.Println(y)
    
        yarr := make([]byte, 8)
        y.FillBytes(yarr)
        fmt.Println(yarr)
    }
    

    Output:

    [1 2 3]
    66051
    68611
    [0 0 0 0 0 1 12 3]