How to convert from []byte to int in Go Programming

Emanuel picture Emanuel · Jun 25, 2012 · Viewed 117.7k times · Source

I need to create a client-server example over TCP. In the client side I read 2 numbers and I send them to the server. The problem I faced is that I can't convert from []byte to int, because the communication accept only data of type []byte.

Is there any way to convert []byte to int or I can send int to the server?

Some sample code will be really appreciated.

Thanks.

Answer

David Budworth picture David Budworth · Oct 25, 2014

(reposting this answer)

You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types

Play

package main

import "fmt"
import "encoding/binary"

func main() {
    var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
    data := binary.BigEndian.Uint64(mySlice)
    fmt.Println(data)
}