doukanwen4114 2015-04-23 23:59
浏览 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-24 00: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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计