Tamerz
Tamerz

Reputation: 947

How do I create a byte array from a mix of hex and strings in Go?

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.

Upvotes: 0

Views: 479

Answers (2)

Uvelichitel
Uvelichitel

Reputation: 8490

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

Upvotes: 1

Tamerz
Tamerz

Reputation: 947

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:

https://blog.golang.org/strings

Upvotes: 0

Related Questions