英文:
How do I create a byte array from a mix of hex and strings in Go?
问题
我正在尝试实现这里指定的数据:
https://developer.valvesoftware.com/wiki/Server_queries#Request_Format
我正在创建一个字节数组,最终需要看起来像这样:
0xFF 0xFF 0xFF 0xFF 0x54 0x53 0x6F 0x75 0x72 0x63 0x65 0x20 0x45 0x6E 0x67 0x69 0x6E 0x65 0x20 0x51 0x75 0x65 0x72 0x79 0x00
简单来说,它只是一个带有一些字节的头部:
0xFF 0xFF 0xFF 0xFF 0x54
然后,在此之后是以零结尾的字符串 "Source Engine Query"。
我能够用一种非常丑陋的方式使其工作,但我知道一定有更简洁的方法:
message := []byte("xxxxxSource Engine Queryx")
message[0] = 0xFF
message[1] = 0xFF
message[2] = 0xFF
message[3] = 0xFF
message[4] = 0x54
message[24] = 0x00
我尝试过使用切片,像这样,但我不知道如何将其与非字符串值一起使用:
message := make([]byte, 25)
copy(message[5:], "Source Engine Query")
这样可以工作,但我不知道如何在开头添加 "0xFF 0xFF 0xFF 0xFF 0x54"。
英文:
I'm trying to implement the data specified here:
https://developer.valvesoftware.com/wiki/Server_queries#Request_Format
I'm creating a byte array that needs to end up looking like this:
0xFF 0xFF 0xFF 0xFF 0x54 0x53 0x6F 0x75 0x72 0x63 0x65 0x20 0x45 0x6E 0x67 0x69 0x6E 0x65 0x20 0x51 0x75 0x65 0x72 0x79 0x00
Broken down, it is just some bytes in a header:
0xFF 0xFF 0xFF 0xFF 0x54
Then after that, the zero terminated string "Source Engine Query".
I was able to get this to work in a very ugly fashion, but I know there has to be a cleaner path:
message := []byte("xxxxxSource Engine Queryx")
message[0] = 0xFF
message[1] = 0xFF
message[2] = 0xFF
message[3] = 0xFF
message[4] = 0x54
message[24] = 0x00
I've tried using slices like this, but I can't figure out how to use it with non string values:
message := make([]byte, 25)
copy(message[5:], "Source Engine Query")
That works, but then I can't figure out how to add the "0xFF 0xFF 0xFF 0xFF 0x54" to the beginning.
答案1
得分: 1
这也是 bytes.Buffer https://golang.org/pkg/bytes/#Buffer 中的一种方法,非常快速,并且有几个方便的方法。
message := bytes.NewBuffer([]byte{0xFF, 0xFF, 0xFF, 0xFF, 0x54})
message.WriteString("Source Engine Query")
message.WriteByte(0x00)
message.WriteTo(os.Stdout) //或者写入其他你想要的 io.Writer,比如 net.Conn
英文:
It's also bytes.Buffer https://golang.org/pkg/bytes/#Buffer among other approaches, quite fast and has couple of handy methods
message := bytes.NewBuffer([]byte{0xFF, 0xFF, 0xFF, 0xFF, 0x54})
message.WriteString("Source Engine Query")
message.WriteByte(0x00)
message.WriteTo(os.Stdout) //or write to some other io.Writer you want, say net.Conn
答案2
得分: 0
在长时间的工作后,当然是在这里询问之后我才弄清楚...
message := []byte("\xff\xff\xff\xff\x54Source Engine Query\x00")
这个代码完美运行。我在这里找到了它:
https://blog.golang.org/strings
英文:
After a long time of working on this, I of course figure it out after I ask here...
message := []byte("\xff\xff\xff\xff\x54Source Engine Query\x00")
This works perfect. I found it here:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论