英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论