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

查看:77
本文介绍了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天全站免登陆