如何从字节数组读取/写入浮点值?
我确信这个问题之前已经被问过很多次了,所以我快速搜索了一下,发现 这个维基百科页面解释了浮点值的结构。
我正在通过网络发送和接收由一些浮点值(用于游戏)组成的数据,这导致我产生以下问题:
- 我是否需要担心字节顺序?
- 如果字节顺序很重要,那么如何在不进行
*(float*)
转换或联合的情况下提取这些值? (例如整数移位的技巧)
提前致谢。
I'm sure this question has been asked many times before, so I did a quick search and found this Wikipedia page that explains the structure of a floating point value.
I'm sending and receiving data across a network that consists of some floating point values (for a game), which leads me to the following questions:
- Do I have to worry about endianness?
- If endianness matters, how can I extract these values without doing a
*(float*)
cast or a union? (such as the trick with bit shifting for integers)
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您直接从内存中写出浮点值,那么,是的,您将必须处理字节顺序。
有上千种方法可以解决这个问题。网络协议经常使用的一种方法是将结构读入字节缓冲区,交换所有元素(如果主机的字节顺序与协议的字节顺序不匹配),然后将其视为正常的主机结构。
If you write out a floating-point value straight from memory, then, yes, you will have to handle endianness.
There are thousand of ways you can handle this. One way often used by network protocols is to read a structure into a byte buffer, swap all elements (if the endianness of the host machine does not match that of the protocol) and then treat it as a normal host-machine structure.