doukanwen4114 2015-04-23 15:59 采纳率: 100%
浏览 230
已采纳

Golang-将int添加到字节数组的末尾

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条回答 默认 最新

  • doutinghou6980 2015-04-23 16:13
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部