英文:
Golang - Add int to end of byte array
问题
我正在尝试在Golang中将一个整数添加到字节数组的末尾。
这是我的当前代码:
nameLengthBytes := []byte{32, 32}
nameLength := len(name)
nameLengthBytes 创建了两个空格,我想要的是一种将nameLength添加到nameLengthBytes末尾的方法。
示例:
如果name的长度为7,我希望数组为:{32, 55}
如果name的长度为12,我希望数组为:{49, 50}
问题是有时name的长度小于10,所以我需要用前导零填充。
英文:
I am trying to add an int to the end of a byte array in Golang.
This is my current code:
nameLengthBytes := []byte{32, 32}
nameLength := len(name)
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:
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}
The problem is that sometimes the name is shorter than 10 so I need to fill up with a leading zero.
答案1
得分: 2
你想要一个以字节形式表示的数字的空格填充的ASCII表示吗?fmt.Sprintf
会生成一个字符串,然后你可以将其转换为字节。
以下是一些代码,或者你可以在playground上运行它。
package main
import "fmt"
func main() {
bs := []byte(fmt.Sprintf("%2d", 7))
fmt.Println(bs)
}
英文:
You want a space-padded ascii representation of a number as bytes? fmt.Sprintf
produces a string, which you can then convert to bytes.
Here's some code, or run it on the playground.
package main
import "fmt"
func main() {
bs := []byte(fmt.Sprintf("%2d", 7))
fmt.Println(bs)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论