C++:如何以与平台无关的方式读写多字节整数值?
我正在开发一个简单的协议,用于从缓冲区读取整数值/向缓冲区写入整数值。绝大多数整数都低于 128,但也可能有更大的值,因此我正在研究某种形式的多字节编码来以简洁的方式存储这些值。
以与平台无关(即字节顺序无关)的方式读取/写入多字节值的最简单、最快的方法是什么?
I'm developing a simple protocol that is used to read/write integer values from/to a buffer. The vast majority of integers are below 128, but much larger values are possible, so I'm looking at some form of multi-byte encoding to store the values in a concise way.
What is the simplest and fastest way to read/write multi-byte values in a platform-independent (i.e. byte order agnostic) way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
XDR 格式可能会帮助您。如果我必须用一句话来概括它,它是一种整数的二进制 UTF-8。
编辑:正如我在下面的评论中提到的,我“了解”XDR,因为我在办公室工作中使用了多个与 XDR 相关的功能。仅在您的评论之后,我才意识到我每天使用的“打包 XDR”格式甚至不是官方 XDR 文档的一部分,因此我将单独描述它。
这个想法是:
我不知道这是否是一种“真正的”格式,或者我的(前)同事自己创建了这个格式(这就是我不发布代码的原因)。
XDR format might help you there. If I had to summarize it in one sentence, it's a kind of binary UTF-8 for integers.
Edit: As mentioned in my comment below, I "know" XDR because I use several XDR-related functions in my office job. Only after your comment I realized that the "packed XDR" format I use every day isn't even part of the official XDR docs, so I'll describe it seperately.
The idea is thus:
I have no idea if this is a "real" format or my (former) coworker created this one himself (which is why I don't post code).
您可能对以下功能感兴趣:
man byteorder
You might be interested in the following functions:
man byteorder
文字将是我的第一选择。如果您想要不同长度的二进制编码,您有两个基本选择:
显然,您可以将它们与某些值位合并。
对于长度指示,可以为您提供长度和一些位一起给出的信息(例如,参见 UTF-8),
对于结束标记,您可以例如声明 MSB 集指示最后一个字节,因此每个字节有 7 个数据位。
其他变体显然是可能的。
Text would be my first choice. If you want a varying length binary encoding you have two basic choices:
You obviously make merge those with some value bits.
For a length indication that would give you something where the length and some bits are given together (see for instance UTF-8),
For an end marker, you can for instance state that MSB set indicates the last byte and thus have 7 data bits per byte.
Other variants are obviously possible.
您可以尝试网络字节顺序
You could try Network Byte Order
Google 的协议缓冲区提供了使用可变宽度编码的预制实现。
Google's protocol buffers provide a pre-made implementation that uses variable-width encodings.