Golang – Add int to end of byte array

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

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

huangapple
  • 本文由 发表于 2015年4月24日 07:59:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/29836433.html
匿名

发表评论

匿名网友

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

确定