is portable aliasing possible in C++?
Andrew Haley
aph@redhat.com
Mon Sep 15 13:21:00 GMT 2014
On 09/15/2014 12:57 PM, Hei Chan wrote:
> // on a big-endian 64-bit machine
>
> struct Message {
> int32_t a;
> int16_t b;
> char c;
> char padding;
> };
>
> // send over a socket
> Message msg = {12345, 678, 'x', 0};
I'd do this:
Message msg = {htonl(12345), htons(678), 'x', 0};
> send(fd, &msg, sizeof Message, 0);
>
>
> // another machine: a little-endian 64-bit machine
> char buffer[1024];
> if (recv(fd, buffer, sizeof buffer, 0)) {
> Message msg;
> // or we can use the union trick
Why not read into the Message?
> memcpy(&msg, buffer, sizeof Message); SomeFunctioToConvertFromBigEndianToSmallEndian(msg.a);
I don't know why you'd want to byte-reverse in place if you actually
care about zero-copy network programming. That makes no sense to me.
Andrew.
More information about the Gcc-help
mailing list