我想在 Golang 中将一个 int 添加到字节数组的末尾。
这是我当前的代码:
nameLengthBytes := []byte{32, 32}
nameLength := len(name)
nameLengthBytes 创建了 2 个空格,我正在寻找一种将 nameLength 添加到 nameLengthBytes 末尾的方法.
示例:
如果名称长度为 7,我希望数组为:{32, 55}
如果名称长度为 12,我希望数组为 {49, 50}
问题是有时名称短于 10,所以我需要用前导零填充。
最佳答案
你想要一个用空格填充的 ascii 表示的数字作为字节? fmt.Sprintf
生成一个字符串,然后您可以将其转换为字节。
这是一些代码,或者 run it on the playground.
package main
import "fmt"
func main() {
bs := []byte(fmt.Sprintf("%2d", 7))
fmt.Println(bs)
}
关于Golang - 将 int 添加到字节数组的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29836433/