为什么这里有一个端序问题

Why is there an endianness problem here?

本文关键字:问题 有一个 这里 为什么      更新时间:2023-10-16

我正在阅读关于指针别名规则的这个线程,一个答案给出了下面的例子,其中提到了端序的潜在问题,我想知道是否有人可以给我什么端序问题是在下面的代码?

struct Msg
{
   unsigned int a;
   unsigned int b;
};
int main()
{
   // Pass data to something; if the implementer of this API were
   // strict-aliasing-aware, he would have taken a char*, not a unsigned int*
   Msg* msg = new Msg();
   msg->a = 1;
   msg->b = 2;
   // stupidBuffer is an alias for msg.
   // yes I know there are endianess problems here (WHY??), but my API is stupid and 
   // only works for one platform
   unsigned int* stupidBuffer = reinterpret_cast<unsigned int*>(msg);
   SendToStupidApi( stupidBuffer );   
}

不存在排序问题。只要StupidApi不涉及通过网络发送它或在平台之间进行序列化,那么根本就不存在端序问题。

消息传递api应该允许您将本地端序转换为网络端序(通常是大端序),然后再转换回来。通过对网络端序有一个约定,任何机器都可以与网络上的任何其他机器通信,而不管它自己的字节顺序如何。

查看您的api或示例。在不了解您使用的是什么产品的情况下,恐怕我们无法为您提供更多的帮助。