如何保留 big.Int.Bytes() 的长度?

huangapple go评论77阅读模式
英文:

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

问题

给定:

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) // []

我尝试将数字1放入其中,并得到了如下结果:

... // [0 0 0 0 0 0 0 1] 来自 []byte

...// [1] 来自 big.Int

我必须保留长度为8,但big.Int不允许这样做。如何能够仍然保留长度?

英文:

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?

答案1

得分: 0

Int类型在内部不保留构造时的字节,并且Bytes方法返回表示该值所需的最小字节数。

为了将其转换为固定长度的字节切片,可以使用FillBytes方法。您需要确保该值适合提供的字节切片,否则会引发错误。

示例:

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)
}

输出:

[1 2 3]
66051
68611
[0 0 0 0 0 1 12 3]
英文:

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]

huangapple
  • 本文由 发表于 2022年4月12日 17:44:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/71840457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定