Data Alignment and Byte Ordering
Tuesday, May 1, 2007 7:10:55 PM
Writing Cross-Platform Software: Getting Started
Data alignment: Straighten up and fly right
Byte Alignment and Ordering
Examples
1. A simple code snippet to test whether a given architecture is big- or little-endian (copy from the book "Linux Kernel Development by Robert Love):
int x = 1; if(*(char *)&x == 1) /* little endian */ else /* big endian */
2. Routines to convert between big-endian and little-endian formats: (copy from Byte Alignment and Ordering)
short convert_short(short in)
{
short out;
char *p_in = (char *) ∈
char *p_out = (char *) &out;
p_out[0] = p_in[1];
p_out[1] = p_in[0];
return out;
}
long convert_long(long in)
{
long out;
char *p_in = (char *) ∈
char *p_out = (char *) &out;
p_out[0] = p_in[3];
p_out[1] = p_in[2];
p_out[2] = p_in[1];
p_out[3] = p_in[0];
return out;
}

Anonymous # Thursday, July 7, 2011 9:23:23 AM