Golang - 将int添加到字节数组的末尾 [英] Golang - Add int to end of byte array

查看:966
本文介绍了Golang - 将int添加到字节数组的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 

我试图在一个字节数组的末尾添加一个int在Golang中。 > nameLengthBytes:= [] byte {32,32}
nameLength:= len(name)


nameLengthBytes 创建2个空格,我正在寻找的是将 nameLength 添加到 nameLengthBytes 即可。

示例:如果名字长度是7,那么
我希望数组是:{32,55} <
如果名字长度是12,我希望数组是{49,50}

问题是有时名字短于10我需要填补一个领先的零。

解决方案

你想要一个以字节为单位的空格填充ascii表示数字吗? fmt.Sprintf 产生一个字符串,然后你可以将它转换为字节。

这里有一些代码,或在操场上运行。

  package main 
$ b $ importfmt

func main(){
bs:= [] byte(fmt.Sprintf( %2d,7))
fmt.Println(bs)
}


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.

解决方案

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

这篇关于Golang - 将int添加到字节数组的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆