Convert an integer to a byte array

前端 未结 5 1186
北荒
北荒 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 22:00

    Adding this option for dealing with basic uint8 to byte[] conversion

    foo := 255 // 1 - 255
    ufoo := uint16(foo) 
    far := []byte{0,0}
    binary.LittleEndian.PutUint16(far, ufoo)
    bar := int(far[0]) // back to int
    fmt.Println("foo, far, bar : ",foo,far,bar)
    

    output : foo, far, bar : 255 [255 0] 255

提交回复
热议问题