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

huangapple go评论127阅读模式
英文:

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

问题

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

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

非常感谢,期待一些示例代码。

英文:

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.

答案1

得分: 125

你可以使用encoding/binary的ByteOrder来处理16、32、64位类型的数据。

Play

  1. package main
  2. import "fmt"
  3. import "encoding/binary"
  4. func main() {
  5. var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
  6. data := binary.BigEndian.Uint64(mySlice)
  7. fmt.Println(data)
  8. }
英文:

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

Play

  1. package main
  2. import "fmt"
  3. import "encoding/binary"
  4. func main() {
  5. var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
  6. data := binary.BigEndian.Uint64(mySlice)
  7. fmt.Println(data)
  8. }

答案2

得分: 21

如果[]byte是ASCII字节数字,则首先将[]byte转换为字符串,然后使用strconv包的Atoi方法将字符串转换为整数。

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func main() {
  7. byteNumber := []byte("14")
  8. byteToInt, _ := strconv.Atoi(string(byteNumber))
  9. fmt.Println(byteToInt)
  10. }

Go playground

英文:

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.

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func main() {
  7. byteNumber := []byte("14")
  8. byteToInt, _ := strconv.Atoi(string(byteNumber))
  9. fmt.Println(byteToInt)
  10. }

Go playground

答案3

得分: 13

从字节数组开始,您可以使用binary包进行转换。

例如,如果您想要读取整数:

  1. buf := bytes.NewBuffer(b) // b是[]byte
  2. myfirstint, err := binary.ReadVarint(buf)
  3. anotherint, err := binary.ReadVarint(buf)

同样的包允许使用通用的Read函数以所需的字节顺序读取无符号整数或浮点数。

英文:

Starting from a byte array you can use the binary package to do the conversions.

For example if you want to read ints :

  1. buf := bytes.NewBuffer(b) // b is []byte
  2. myfirstint, err := binary.ReadVarint(buf)
  3. 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.

答案4

得分: 10

现在 := []byte{0xFF,0xFF,0xFF,0xFF}
现在缓冲区 := bytes.NewReader(现在)
var 现在变量 uint32
binary.Read(现在缓冲区,binary.BigEndian,&现在变量)
fmt.Println(现在变量)

英文:
  1. now := []byte{0xFF,0xFF,0xFF,0xFF}
  2. nowBuffer := bytes.NewReader(now)
  3. var nowVar uint32
  4. binary.Read(nowBuffer,binary.BigEndian,&nowVar)
  5. fmt.Println(nowVar)
  1. 4294967295

答案5

得分: 9

math/big提供了一种简单易用的方法将二进制切片转换为数字。

  1. package main
  2. import (
  3. "fmt"
  4. "math/big"
  5. )
  6. func main() {
  7. b := []byte{0x01, 0x00, 0x01}
  8. v := int(big.NewInt(0).SetBytes(b).Uint64())
  9. fmt.Printf("%v", v)
  10. }
英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. "math/big"
  5. )
  6. func main() {
  7. b := []byte{0x01, 0x00, 0x01}
  8. v := int(big.NewInt(0).SetBytes(b).Uint64())
  9. fmt.Printf("%v", v)
  10. }

答案6

得分: 6

对于将数字编码/解码为字节序列,可以使用encoding/binary包。文档中有一些示例:请参阅目录中的示例部分。

这些编码函数操作io.Writer接口。net.TCPConn类型实现了io.Writer,因此您可以直接向网络连接写入/读取。

如果您在连接的两端都有一个Go程序,您可能希望考虑使用encoding/gob。请参阅文章“Gobs of data”以了解使用gob的步骤(跳到底部查看一个完整的示例)。

英文:

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

答案7

得分: 3

使用位运算符而不需要额外的依赖库

  1. func toInt(bytes []byte) int {
  2. result := 0
  3. for i := 0; i < 4; i++ {
  4. result = result << 8
  5. result += int(bytes[i])
  6. }
  7. return result
  8. }
英文:

Using bitwise operator without additional dependencies

  1. func toInt(bytes []byte) int {
  2. result := 0
  3. for i := 0; i &lt; 4; i++ {
  4. result = result &lt;&lt; 8
  5. result += int(bytes[i])
  6. }
  7. return result
  8. }

答案8

得分: 1

如果[]byte数组中的字节是从0到9的ASCII字符,你可以在循环中将它们转换为int

  1. var value int
  2. for _, b := range []byte{48, 49, 50, 51, 52} {
  3. value = value*10 + int(b-48)
  4. }
  5. fmt.Printf("整数值:%d", value)

Go Playground

英文:

If bytes in the []byte array are ASCII characters from 0 to 9 you can convert them to an int in a loop:

  1. var value int
  2. for _, b := range []byte{48, 49, 50, 51, 52} {
  3. value = value*10 + int(b-48)
  4. }
  5. fmt.Printf(&quot;integer value: %d&quot;, value)

Go Playground

答案9

得分: 0

encoding/binary中的binary.Read提供了将字节数组转换为数据类型的机制。

请注意,网络字节顺序是大端序,所以在这种情况下,您需要指定binary.BigEndian

  1. package main
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. )
  7. func main() {
  8. var myInt int
  9. b := []byte{0x18, 0x2d} // 这也可以是一个流
  10. buf := bytes.NewReader(b)
  11. err := binary.Read(buf, binary.BigEndian, &myInt) // 确保您知道数据是小端序还是大端序
  12. if err != nil {
  13. fmt.Println("binary.Read failed:", err)
  14. return
  15. }
  16. fmt.Print(myInt)
  17. }

查看这个文档可能会有帮助:https://pkg.go.dev/encoding/binary@go1.17.1#Read

英文:

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.

  1. package main
  2. import (
  3. &quot;bytes&quot;
  4. &quot;encoding/binary&quot;
  5. &quot;fmt&quot;
  6. )
  7. func main() {
  8. var myInt int
  9. b := []byte{0x18, 0x2d} // This could also be a stream
  10. buf := bytes.NewReader(b)
  11. err := binary.Read(buf, binary.BigEndian, &amp;myInt) // Make sure you know if the data is LittleEndian or BigEndian
  12. if err != nil {
  13. fmt.Println(&quot;binary.Read failed:&quot;, err)
  14. return
  15. }
  16. fmt.Print(myInt)
  17. }

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

huangapple
  • 本文由 发表于 2012年6月25日 14:24:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/11184336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定