在Go语言中,与Python中的bytes()或bytearray()函数对应的是[]byte类型。

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

Python bytes() or bytesarray() counterpart in golang

问题

我正在寻找将一些Python代码转换为Go的方法。Python代码如下所示:

to_be_converted = [3, 40, 234, 1, 23, 65, 43, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
converted = bytes(to_be_converted)
print(converted)

这将输出:

b'\x03(\xea\x01\x17A+Hello world'

我正在寻找一种在Go中获取这个字节对象的方法。我不介意输入数据是否不同,我只是想找到获取输出的方法。谢谢。

英文:

I am looking to port some code from python into golang.
The code in python goes like this

to_be_converted = [3, 40, 234, 1, 23, 65, 43, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
converted = bytes(to_be_converted)
print(converted)

this results to

b'\x03(\xea\x01\x17A+Hello world'

I am looking for a way to get this bytes object in golang.
I dont mind if the input data is different, I am only looking for a way to obtain the output.
Thank you

答案1

得分: 3

Go语言有一个内置的byte类型,你可以像这样创建byte数组:

myBytes := []byte{3, 40, 234, 1, 23, 65, 43, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100}

要获取字符串输出,你可以将byte数组转换为字符串,像这样:

myString := string(myBytes)
fmt.Println(myString) // 输出 (�A+Hello world
英文:

Go has a builtin byte type and you can create byte arrays like this:

myBytes := []byte{3, 40, 234, 1, 23, 65, 43, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100}

To get the string output, you can just convert the byte array to a string like this:

myString := string(myBytes)
fmt.Println(myString)// prints (�A+Hello world

huangapple
  • 本文由 发表于 2022年2月16日 21:23:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/71142678.html
匿名

发表评论

匿名网友

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

确定