75

I have a function which receives a []byte but 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.

0

12 Answers 12

81

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)
}
1
  • Ended up using a small variation of your first suggestion. Should have dived into the implementation myself, thanks for the tip.
    – vascop
    Commented Jun 17, 2013 at 19:28
39

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

binary.Write(a, binary.LittleEndian, myInt)
4
  • 8
    After benchmarking the "enconding/binary" way, it takes almost 4 times longer than int -> string -> byte
    – vascop
    Commented Jun 3, 2013 at 0:22
  • 7
    But what byte representation does your consumer expect for integers? Surely not the ASCII representation? Please clarify.
    – dyoo
    Commented Jun 3, 2013 at 4:56
  • 1
    @vascop it does. But binary.LittleEndian.PutUint64(bs, value) is much faster than int -> string -> byte. Commented Sep 20, 2016 at 6:02
  • 2
    Make sure to check the err returned by binary.Write, see @Agniva De Sarker's answer. Does not work directly with the int type, you need to cast it to int64 or something similar.
    – aleb
    Commented Jan 19, 2017 at 15:04
32

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())
1
  • this answer should be on top, it is the only meaningful one.
    – Tchakabam
    Commented Dec 16, 2022 at 2:36
3

i thought int type has any method for getting int hash to bytes, but first i find math / big method for this https://golang.org/pkg/math/big/

var f int = 52452356235;          // int
var s = big.NewInt(int64(f))      // int to big Int
var b = s.Bytes()                 // big Int to bytes
// b - byte slise
var r = big.NewInt(0).SetBytes(b) // bytes to big Int
var i int = int(r.Int64())        // big Int to int

https://play.golang.org/p/VAKSGw8XNQq

However, this method uses an absolute value. If you spend 1 byte more, you can transfer the sign

func IntToBytes(i int) []byte{
    if i > 0 {
        return append(big.NewInt(int64(i)).Bytes(), byte(1))
    }
    return append(big.NewInt(int64(i)).Bytes(), byte(0))
}
func BytesToInt(b []byte) int{
    if b[len(b)-1]==0 {
        return -int(big.NewInt(0).SetBytes(b[:len(b)-1]).Int64())
    }
    return int(big.NewInt(0).SetBytes(b[:len(b)-1]).Int64())
}

https://play.golang.org/p/mR5Sp5hu4jk

or new(https://play.golang.org/p/7ZAK4QL96FO)

(The package also provides functions for fill into an existing slice)

https://golang.org/pkg/math/big/#Int.FillBytes

2

Here is another option, based on the Go source code [1]:

package main

import (
   "encoding/binary"
   "fmt"
   "math/bits"
)

func encodeUint(x uint64) []byte {
   buf := make([]byte, 8)
   binary.BigEndian.PutUint64(buf, x)
   return buf[bits.LeadingZeros64(x) >> 3:]
}

func main() {
   for x := 0; x <= 64; x += 8 {
      buf := encodeUint(1<<x-1)
      fmt.Println(buf)
   }
}

Result:

[]
[255]
[255 255]
[255 255 255]
[255 255 255 255]
[255 255 255 255 255]
[255 255 255 255 255 255]
[255 255 255 255 255 255 255]
[255 255 255 255 255 255 255 255]

Much faster than math/big:

BenchmarkBig-12         28348621                40.62 ns/op
BenchmarkBit-12         731601145                1.641 ns/op
  1. https://github.com/golang/go/blob/go1.16.5/src/encoding/gob/encode.go#L113-L117
1

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

1

This is the most straight forward (and shortest (and safest) (and maybe most performant)) way:

buf.Bytes() is of type bytes slice.

    var val uint32 = 42
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.LittleEndian, val)
    if err != nil {
        fmt.Println("binary.Write failed:", err)
    }
    fmt.Printf("% x\n", buf.Bytes())

see also https://stackoverflow.com/a/74819602/589493

1
0

Convert Integer to byte slice.

import (
    "bytes"
    "encoding/binary"
    "log"
)

func IntToBytes(num int64) []byte {
    buff := new(bytes.Buffer)
    bigOrLittleEndian := binary.BigEndian
    err := binary.Write(buff, bigOrLittleEndian, num)
    if err != nil {
        log.Panic(err)
    }

    return buff.Bytes()
}
0

Maybe the simple way is using protobuf, see the Protocol Buffer Basics: Go

define message like

message MyData {
  int32 id = 1;
}

get more in Defining your protocol format

// Write
out, err := proto.Marshal(mydata)

read more in Writing a Message

0

Try math/big package to convert bytes array to int and to convert int to bytes array.

package main

import (
    "fmt"
    "math/big"
)

func main() {
    // Convert int to []byte
    var int_to_encode int64 = 65535
    var bytes_array []byte = big.NewInt(int_to_encode).Bytes()
    fmt.Println("bytes array", bytes_array)

    // Convert []byte to int
    var decoded_int int64 = new(big.Int).SetBytes(bytes_array).Int64()
    fmt.Println("decoded int", decoded_int)
}


0

Step 1. Ignore endianness, and do it directly for any type:

func toBytes[T any](val T) []byte {
    return unsafe.Slice((*byte)(unsafe.Pointer(&val)), unsafe.Sizeof(val))
}

(also consider adding Integer constraint on type T)

Step 2. Do you really need portability between machines with different endianness? Ok, here's an idea:

func toLEBytes[T any](val T) []byte {
    bytes := toBytes(val)
    if runningOnBigEndian() {
        slices.Reverse(bytes)
    }
    return bytes
}

The only thing you need is to implement runningOnBigEndian(). Start by reading this question answers: Any better way to check endianness in Go

Also note that reversing bytes is fine, because endianness is the order or sequence of bytes, not bits.

Endian example

-6

What's wrong with converting it to a string?

[]byte(fmt.Sprintf("%d", myint))
4
  • 6
    This encodes the ASCII representation of the number, not the number itself.
    – Matt
    Commented Apr 1, 2018 at 1:04
  • fmt.Sprintf is 2 times slower than the following code play.golang.org/p/g-yTtgOxeNT if you are ready to give up the decimal representation
    – Larytet
    Commented Jun 8, 2018 at 16:30
  • @Matt ah Thank you :) Commented Jul 30, 2019 at 21:58
  • Pushing Larytet's solution a little faster: play.golang.org/p/JZ8CBVf6QNO Commented Jan 14, 2021 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.