Tony The Lion
Tony The Lion

Reputation: 63190

Why is there an endianness problem here?

I was reading up on this thread on pointer aliasing rules, and one answer gives the following example, which mentions a potential problem with endianness, I wanted to know if anyone could give me what the endianness problem is in the following code?

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 );   
}

Upvotes: 0

Views: 238

Answers (2)

Rob
Rob

Reputation: 2656

Your messaging api should allow you to convert your local endianess to the network endianess (usually big endian) and back. By having a convention for the networking endianess, any machine can talk to any ohter machine on your network regardless of its own byte ordering.

Look in your api or examples for this. without knowing what you are using I am afraid we cannot help you much further than this.

Upvotes: 0

Puppy
Puppy

Reputation: 146910

There isn't any endianness problem. As long as StupidApi doesn't involve sending it over a network or serialization between platforms, then there's no endianness issue at all.

Upvotes: 10

Related Questions