gpt4 book ai didi

c++ - 没有 htonl/ntohl 的 union 和字节顺序

转载 作者:可可西里 更新时间:2023-11-01 02:33:44 24 4
gpt4 key购买 nike

我想解析我收到的 TCP 包的 header 。

假设这是一个头部结构:

(2 bytes for commands) + (2 bytes for token) + (4 bytes for data length)
Example of package: 0x01 0x02 0x12 0x34 0x00 0x00 0x00 0x05
There 0x0102 is command, 0x1234 is token and 0x000005 is data length.

我想在 Windows 平台上以有效的方式解析此 header 。我为这个标题创建了下一个 union :

typedef union
{
struct
{
uint16_t command;
uint16_t token;
uint32_t data_length;
} field;
char bytes[8];
} MyHeader_t;

MyHeader_t bar;
read_8_bytes(bar.bytes);
std::cout << bar.fields.token << std::endl;

接下来,我尝试将上面的包复制到我的 bytes 数组。但是网络包是大字节序的,PC 试图以小字节序读取字段。结果,我的 token 字段等于 0x3412(而不是 0x1234)。

如何使用单独的字节序来避免这个问题?

最佳答案

Boost 提供了一个专用于字节顺序的库:

http://www.boost.org/doc/libs/1_61_0/libs/endian/doc/index.html

例如:

boost::endian::big_to_native_inplace(bar.field.command);

或由 AndyG:

std::cout << boost::endian::endian_reverse(bar.field.token) << std::endl;

注意:这个库有 3 种处理字节序的方法,你需要花时间选择适合你的情况。

关于c++ - 没有 htonl/ntohl 的 union 和字节顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44330429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com