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.
Best Answer
You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types
Play
package mainimport "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)}
If []byte is ASCII byte numbers then first convert the []byte to string and use the strconv
package Atoi
method which convert string to int.
package mainimport ("fmt""strconv")func main() {byteNumber := []byte("14")byteToInt, _ := strconv.Atoi(string(byteNumber))fmt.Println(byteToInt)}
Go playground
Starting from a byte array you can use the binary package to do the conversions.
For example if you want to read ints :
buf := bytes.NewBuffer(b) // b is []bytemyfirstint, err := binary.ReadVarint(buf)anotherint, err := binary.ReadVarint(buf)
The same package allows the reading of unsigned int or floats, with the desired byte orders, using the general Read function.
now := []byte{0xFF,0xFF,0xFF,0xFF}nowBuffer := bytes.NewReader(now)var nowVar uint32binary.Read(nowBuffer,binary.BigEndian,&nowVar)fmt.Println(nowVar)
4294967295
The math/big
provides a simple and easy way to convert a binary slice to a numberplayground
package mainimport ("fmt""math/big")func main() {b := []byte{0x01, 0x00, 0x01}v := int(big.NewInt(0).SetBytes(b).Uint64())fmt.Printf("%v", v)}
For encoding/decoding numbers to/from byte sequences, there's the encoding/binary package. There are examples in the documentation: see the Examples section in the table of contents.
These encoding functions operate on io.Writer interfaces. The net.TCPConn type implements io.Writer, so you can write/read directly to network connections.
If you've got a Go program on either side of the connection, you may want to look at using encoding/gob. See the article "Gobs of data" for a walkthrough of using gob (skip to the bottom to see a self-contained example).
Using bitwise operator without additional dependencies
func toInt(bytes []byte) int {result := 0for i := 0; i < 4; i++ {result = result << 8result += int(bytes[i])}return result}
If bytes in the []byte
array are ASCII characters from 0 to 9 you can convert them to an int
in a loop:
var value intfor _, b := range []byte{48, 49, 50, 51, 52} {value = value*10 + int(b-48)}fmt.Printf("integer value: %d", value)
Go Playground
binary.Read
in encoding/binary
provides mechanisms to convert byte arrays to datatypes.
Note that Network Byte Order is BigEndian, so in this case, you'll want to specify binary.BigEndian
.
package mainimport ("bytes""encoding/binary""fmt")func main() {var myInt intb := []byte{0x18, 0x2d} // This could also be a streambuf := bytes.NewReader(b)err := binary.Read(buf, binary.BigEndian, &myInt) // Make sure you know if the data is LittleEndian or BigEndianif err != nil {fmt.Println("binary.Read failed:", err)return}fmt.Print(myInt)}
Reviewing this documentation may be helpful: https://pkg.go.dev/encoding/[email protected]#Read