Click to See Complete Forum and Search --> : char array and endian concern


tim24
July 8th, 2009, 10:04 PM
Hi all,

I got 2 programs running on 2 different machines.
program A set some configs to buffer and sends the buffer to program B. B read the buffer and display the config.

A and B both cast the buffer to a structure and then access structure's fields.

char buffer[128];

struct xx
{
int32 i;
int32 j;
char str[64];
}

For example:
xx *ptr= (xx*)bufffer;
xx->i = 1000;
xx->j= 6742;



So far I don't have problem because both machines running on PPC (big endian).
Now if A has also to be run on an Intel (little endian), what should I do to take care of this?


thanks in advance.

Clairvoyant1332
July 9th, 2009, 07:32 AM
What you need to do is convert the integers in your struct to network byte order before sending, then back to host byte order after you receive it. Since the int fields are 32 bit, use htonl() to switch to network byte order and ntohl to switch to host byte order.