<ju**********@yahoo.co.inwrote in message
news:11**********************@80g2000cwy.googlegro ups.com...
Hi guys,
I need to convert a big endian integer to little endian integer.
(the integer is 4 bytes in size on my implementation). I came up with
the following code. I need your comments on this. Please suggest any
improvements that can be done.
#include <stdio.h>
int main(void)
{
int big = 0x12345678;
int little;
char *big_ptr = (char *)&big;
char *little_ptr = (char *)&little;
little_ptr[0] = big_ptr[3];
little_ptr[1] = big_ptr[2];
little_ptr[2] = big_ptr[1];
little_ptr[3] = big_ptr[0];
printf("big = 0x%x little = 0x%x\n",big,little);
}
The code above should work fine. However, the more traditional approach is
to use a union, i.e.
union
{
int i;
char c[4];
} pickapart;
pickapart.i = input_arg;
output0 = pickapart.c[0];
However, if you can find an approach involving shifting only, and if an
examination of the assembly-language shows that the compiler does it well
(probably without shifting), that would be the preferred approach, i.e.
output0 = input_arg & 0xFF;
output1 = (input_arg >>8) & 0xFF;
etc.
then that would be the preferred approach. The approach you cited can lead
to memory addressing problems if the int size is <32, and the approach I
cited with the union won't work for other sizes of integers. There should
be a more portable and general approach.