unsigned int convertEndianness(unsigned int data) {
char * c;
char temp;
unsigned int test = 0x000000FF;
if((char*)(&test)[0] == (char)(0xFF)) // this machine is little endian
{
c = (char*)(&data);
temp = c[0];
c[0] = c[3];
c[3] = temp;
temp = c[1];
c[1] = c[2];
c[2] = temp;
}
return data;
}
When programming across networks it is often necessary to transfer data between a machine that is little endian and a machine that is big endian. See the Wikipedia entry for more information on the subject.
Generally network transmission should be in big endian. This function will prep data for sending across the network and do the reverse for data recieved across the network. This way the endianness of the opposite machine does not matter. First it checks to see if the first byte is the same as the least significant byte. If this is the case then the machine is little endian and the data must be converted.













