Convert an integer to a byte array

前端 未结 5 1169
北荒
北荒 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:37

    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.

    func Write(w io.Writer, order ByteOrder, data interface{}) error {
        // Fast path for basic types.
        var b [8]byte
        var bs []byte
        switch v := data.(type) {
        case *int8:
            bs = b[:1]
            b[0] = byte(*v)
        case int8:
            bs = b[:1]
            b[0] = byte(v)
        case *uint8:
            bs = b[:1]
            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)
    }
    
    0 讨论(0)
  • 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())
    
    0 讨论(0)
  • 2020-12-04 21:50

    Check out the "encoding/binary" package. Particularly the Read and Write functions:

    binary.Write(a, binary.LittleEndian, myInt)
    
    0 讨论(0)
  • 2020-12-04 21:50

    What's wrong with converting it to a string?

    []byte(fmt.Sprintf("%d", myint))
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题