在 Go 编程中如何将[]字节转换为 int

我需要通过 TCP 创建一个客户机-服务器示例。在客户端,我读取2个数字并将它们发送到服务器。我遇到的问题是我不能从 []byte转换到 int,因为通信只接受 []byte类型的数据。

有没有办法把 []byte转换成 int或者我可以把 int发送到服务器?

一些示例代码将非常受欢迎。

谢谢。

185393 次浏览

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 []byte
myfirstint, 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.

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).

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

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 main
import (
"fmt"
"strconv"
)


func main() {
byteNumber := []byte("14")
byteToInt, _ := strconv.Atoi(string(byteNumber))
fmt.Println(byteToInt)
}

Go playground

now := []byte{0xFF,0xFF,0xFF,0xFF}
nowBuffer := bytes.NewReader(now)
var  nowVar uint32
binary.Read(nowBuffer,binary.BigEndian,&nowVar)
fmt.Println(nowVar)
4294967295

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 main


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


func main() {
var myInt int
b := []byte{0x18, 0x2d} // This could also be a stream
buf := bytes.NewReader(b)
err := binary.Read(buf, binary.BigEndian, &myInt) // Make sure you know if the data is LittleEndian or BigEndian
if err != nil {
fmt.Println("binary.Read failed:", err)
return
}
fmt.Print(myInt)
}

Reviewing this documentation may be helpful: https://pkg.go.dev/encoding/binary@go1.17.1#Read

The math/big provides a simple and easy way to convert a binary slice to a number playground

package main
import (
"fmt"
"math/big"
)
func main() {


b := []byte{0x01, 0x00, 0x01}


v := int(big.NewInt(0).SetBytes(b).Uint64())


fmt.Printf("%v", v)
}

Using bitwise operator without additional dependencies

func toInt(bytes []byte) int {
result := 0
for i := 0; i < 4; i++ {
result = result << 8
result += int(bytes[i])


}


return result
}