英文:
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位类型的数据。
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)
}
英文:
You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types
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)
}
答案2
得分: 21
如果[]byte是ASCII字节数字,则首先将[]byte转换为字符串,然后使用strconv
包的Atoi
方法将字符串转换为整数。
package main
import (
"fmt"
"strconv"
)
func main() {
byteNumber := []byte("14")
byteToInt, _ := strconv.Atoi(string(byteNumber))
fmt.Println(byteToInt)
}
英文:
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)
}
答案3
得分: 13
从字节数组开始,您可以使用binary包进行转换。
例如,如果您想要读取整数:
buf := bytes.NewBuffer(b) // b是[]byte
myfirstint, err := binary.ReadVarint(buf)
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 :
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.
答案4
得分: 10
现在 := []byte{0xFF,0xFF,0xFF,0xFF}
现在缓冲区 := bytes.NewReader(现在)
var 现在变量 uint32
binary.Read(现在缓冲区,binary.BigEndian,&现在变量)
fmt.Println(现在变量)
英文:
now := []byte{0xFF,0xFF,0xFF,0xFF}
nowBuffer := bytes.NewReader(now)
var nowVar uint32
binary.Read(nowBuffer,binary.BigEndian,&nowVar)
fmt.Println(nowVar)
4294967295
答案5
得分: 9
math/big
提供了一种简单易用的方法将二进制切片转换为数字。
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)
}
英文:
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)
}
答案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
使用位运算符而不需要额外的依赖库
func toInt(bytes []byte) int {
result := 0
for i := 0; i < 4; i++ {
result = result << 8
result += int(bytes[i])
}
return result
}
英文:
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
}
答案8
得分: 1
如果[]byte
数组中的字节是从0到9的ASCII字符,你可以在循环中将它们转换为int
:
var value int
for _, b := range []byte{48, 49, 50, 51, 52} {
value = value*10 + int(b-48)
}
fmt.Printf("整数值:%d", value)
英文:
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 int
for _, b := range []byte{48, 49, 50, 51, 52} {
value = value*10 + int(b-48)
}
fmt.Printf("integer value: %d", value)
答案9
得分: 0
encoding/binary
中的binary.Read
提供了将字节数组转换为数据类型的机制。
请注意,网络字节顺序是大端序,所以在这种情况下,您需要指定binary.BigEndian
。
package main
import (
"bytes"
"encoding/binary"
"fmt"
)
func main() {
var myInt int
b := []byte{0x18, 0x2d} // 这也可以是一个流
buf := bytes.NewReader(b)
err := binary.Read(buf, binary.BigEndian, &myInt) // 确保您知道数据是小端序还是大端序
if err != nil {
fmt.Println("binary.Read failed:", err)
return
}
fmt.Print(myInt)
}
查看这个文档可能会有帮助: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
.
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论