Convert an integer to a byte array

前端 未结 5 1210
北荒
北荒 2020-12-04 21:11

I have a function which receives a []byte but I what I have is an int, what is the best way to go about this conversion?

err = a.Wr         


        
5条回答
  •  执念已碎
    2020-12-04 21:49

    Sorry, this might be a bit late. But I think I found a better implementation on the go docs.

    buf := new(bytes.Buffer)
    var num uint16 = 1234
    err := binary.Write(buf, binary.LittleEndian, num)
    if err != nil {
        fmt.Println("binary.Write failed:", err)
    }
    fmt.Printf("% x", buf.Bytes())
    

提交回复
热议问题