download92000 2019-09-03 01:50
浏览 164

将uint32的字节附加到字节片吗?

If I have an existing []byte, what is the recommended way to append the bytes of one or more uint32 value(s) to it?

For example, what should I replace // ??? with:

s := []byte{0x00, 0x01, 0x02, 0x03}

u := uint32(0x07060504)
// ???

fmt.Println(s)  // Should print [0 1 2 3 4 5 6 7]

Edit: One option would be s = append(s, byte(u)); s = append(s, byte(u >> 8)); s = append(s, byte(u >> 16)); s = append(s, byte(u >> 24)), but is there a more idiomatic way to do this? Perhaps using package binary and/or package bytes?

  • 写回答

3条回答 默认 最新

  • drtpbx3606 2019-09-03 01:56
    关注

    encoding/binary has the functions you need:

    import "encoding/binary"
    
    b := make([]byte,4)
    binary.LittleEndian.PutUint32(b, u)
    s = append(s, b)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题