Golang - 将int添加到字节数组的末尾 [英] Golang - Add int to end of byte array
问题描述
我试图在一个字节数组的末尾添加一个int在Golang中。 >
nameLengthBytes:= [] byte {32,32}
nameLength:= len(name)
nameLengthBytes 创建2个空格,我正在寻找的是将 nameLength 添加到 nameLengthBytes 即可。
示例:如果名字长度是7,那么 问题是有时名字短于10我需要填补一个领先的零。 你想要一个以字节为单位的空格填充ascii表示数字吗? 这里有一些代码,或在操场上运行。 I am trying to add an int to the end of a byte array in Golang. The nameLengthBytes creates 2 spaces, and what I'm looking for is a way to add the nameLength to the end of the nameLengthBytes. Examples: The problem is that sometimes the name is shorter than 10 so I need to fill up with a leading zero. You want a space-padded ascii representation of a number as bytes? Here's some code, or run it on the playground.
这篇关于Golang - 将int添加到字节数组的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
我希望数组是:{32,55} <
如果名字长度是12,我希望数组是{49,50}
fmt.Sprintf
产生一个字符串,然后你可以将它转换为字节。
package main
$ b $ importfmt
func main(){
bs:= [] byte(fmt.Sprintf( %2d,7))
fmt.Println(bs)
}
This is my current code: nameLengthBytes := []byte{32, 32}
nameLength := len(name)
if name length is 7, I want the array to be: {32, 55}
If name length is 12, I want the array to be {49, 50}fmt.Sprintf
produces a string, which you can then convert to bytes.package main
import "fmt"
func main() {
bs := []byte(fmt.Sprintf("%2d", 7))
fmt.Println(bs)
}