【问题标题】:short int to unsigned int conversion network byte order C++short int 到 unsigned int 转换网络字节顺序 C++
【发布时间】:2025-12-22 02:15:07
【问题描述】:

我有一个两字节短整型指针数组short int* hostdata,并希望将其转换为网络字节顺序为unsigned int* net_data 的四字节无符号整型。我这样写可以吗:

for(int i = 0; i < numsamples; ++i)
  net_data[i] = htonl((unsigned int)hostdata[i]);

或者我应该像这样使用 reinterpret_cast 来做:

for(int i = 0; i < numsamples; ++i)
  net_data[i] = htonl(reinterpret_cast<unsigned int *>(reinterpret_cast<short int*>hostdata[i]));

【问题讨论】:

  • 您的 2 个代码示例似乎并不等同于我,因为您在没有取消引用的情况下在第二个示例中转换为指针 - 有意?另外,您想实现哪种转换? short int 可以有负数, unsigned int 不能 - 在这种情况下你会更喜欢下溢吗?截断?重新诠释?
  • 你想对负值做什么?
  • 您有指针数组short int *hostdata[SIZE],还是数字数组short int hostdata[SIZE]?如果是后者,你想用负数做什么?
  • @Joni 根据他的编辑,他没有 - 只是一个指向 short int 的指针(指针和数组相同)
  • @griffin "short int pointer array" 听起来仍然很像指向short int 的指针数组。第二个示例仍然将数组值解释为指针。

标签: c++ networking byte unsigned short


【解决方案1】:

如果您使用的是short integers,那么既然可以使用htons,为什么还要使用htonl

  • htonl 代表主机到网络长

  • htons 代表主机到网络短

请记住,几乎所有 h,n,l,s 的组合都存在,除了像 stonhl 这样愚蠢的组合

不要使事情过于复杂,将它们添加到结构中并按原样发送。

struct MsgHead
{
    unsigned short utype;
    unsigned short usize;
};

// 8 bytes, no padding will be added by the compiler
struct MyPacket
{
    // Header (optional)
    MsgHead        head; // 4 bytes
    unsigned short myData[2]; // 4 bytes
};

【讨论】:

  • 实际上我正在尝试将 2 字节格式数据(短整数)存储为 4 字节格式(整数)。我不应该使用 htonl 吗?
  • @AvbAvb 使用struct 保存shorts 和htons 将它们转换为网络顺序。