C# 如何写入从索引 x 开始的字节数组
我有一个自定义协议来通过 TCP 发送和接收消息,如下所示:
前 4 个字节是消息类型,接下来的 4 个字节是消息的长度,缓冲区的其余部分包含消息本身。
private byte[] CreateMessage(int mtype,string data)
{
byte[] buffer = new byte[4 + 4 + data.Length];
//write mtype, data.Length, and data to buffer
return buffer;
}
我想将 mtype 写入缓冲区的前 4 个字节,然后将 data.Length 写入接下来的 4 个字节,然后写入数据。我来自 golang 世界,我们这样做如下:
buf := make([]byte, 4+4+len(data))
binary.LittleEndian.PutUint32(buf[0:], uint32(mtype))
binary.LittleEndian.PutUint32(buf[4:], uint32(len(data)))
I have a custom protocol to send and receive messages over TCP like the following:
The first 4 bytes is the message type, the following 4 bytes is the length of the message and the rest of the buffer is containing the message itself.
private byte[] CreateMessage(int mtype,string data)
{
byte[] buffer = new byte[4 + 4 + data.Length];
//write mtype, data.Length, and data to buffer
return buffer;
}
I want to write mtype to the first 4 bytes of buffer and then data.Length to next 4 bytes and then the data. I am coming from golang world and we do that like the following:
buf := make([]byte, 4+4+len(data))
binary.LittleEndian.PutUint32(buf[0:], uint32(mtype))
binary.LittleEndian.PutUint32(buf[4:], uint32(len(data)))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
跨度有点像数组,您可以从数组创建跨度……但是跨度可以在内部进行切片。并非所有 API 都可以使用 Span,但那些可以使用的 API ……很不错。
A span is sort of like an array, and you can create a span from an array..but a span can be sliced internally. Not all APIs work with spans, but those that do ... sweet.