tcpclient-serverbytetype-conversiongo

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


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.


Solution

  • 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)
    }