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.Write([]byte(myInt))
I guess I could go the long way and get it into a string and put that into bytes, but it sounds ugly and I guess there are better ways to do it.
I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary
library. The OP suggests that binary.Write()
might have some overhead. Looking at the source for the implementation of Write()
, I see that it does some runtime decisions for maximum flexibility.
189 func Write(w io.Writer, order ByteOrder, data interface{}) error {
190 // Fast path for basic types.
191 var b [8]byte
192 var bs []byte
193 switch v := data.(type) {
194 case *int8:
195 bs = b[:1]
196 b[0] = byte(*v)
197 case int8:
198 bs = b[:1]
199 b[0] = byte(v)
200 case *uint8:
201 bs = b[:1]
202 b[0] = *v
...
Right? Write() takes in a very generic data
third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write()
is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.
Something like this:
package main
import (
"encoding/binary"
"fmt"
)
func main() {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, 31415926)
fmt.Println(bs)
}
Let us know how this performs.
Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa
) and cast that string to the []byte
type.
package main
import (
"fmt"
"strconv"
)
func main() {
bs := []byte(strconv.Itoa(31415926))
fmt.Println(bs)
}
Check out the "encoding/binary" package. Particularly the Read and Write functions:
binary.Write(a, binary.LittleEndian, myInt)
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())
What's wrong with converting it to a string?
[]byte(fmt.Sprintf("%d", myint))