如何在 Go 编程中将 []byte 转换为 int [英] How to convert from []byte to int in Go Programming

查看:22
本文介绍了如何在 Go 编程中将 []byte 转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有什么方法可以将 []byte 转换为 int 或者我可以将 int 发送到服务器?

Is there any way to convert []byte to int or I can send int to the server?

一些示例代码将不胜感激.

Some sample code will be really appreciated.

谢谢.

推荐答案

(转贴 这个答案)

您可以使用 encoding/binary 的 ByteOrder 为 16、32、64位类型

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

这篇关于如何在 Go 编程中将 []byte 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆