1 /* byteSwap.c 2 This program is to show how to swap bytes in a numeric variable for the 3 purposes of solving the byte ordering issues due to the difference in 4 implementations on big-endian and little-endian machines. 5 The key point illustrated in byteSwap() is how to treat an integer as a 6 character array, so that bytes in the array can be swapped. 7 */ 8 #include 9 #include 10 byteSwap(int in, int *out) 11 { 12 int i, pos, siz = sizeof(int); 13 char temp, cary[siz]; 14 bcopy((char *)&in, cary, siz); /* cast and copy an int to a char array */ 15 pos = siz - 1; 16 for (i = 0; i < siz/2; i++) { /* swap bytes in this char array */ 17 temp = cary[i]; 18 cary[i] = cary[pos]; 19 cary[pos--] = temp; 20 } 21 bcopy(cary, (char *)out, siz); /* copy the swapped cary to an int */ 22 } /* byteSwap */ 23 /* A driver to test byteSwap() 24 The following numbers show the values before and after byte swaps. 25 26 From |00000100|00000011|00000010|00000001| -- 67,305,985 27 To |00000001|00000010|00000011|00000100| -- 16,909,060 28 */ 29 int main() 30 { 31 union { 32 int i; 33 short s[2]; 34 } si; 35 int i; 36 si.s[0] = 0x0201; /* |00000010|00000001| */ 37 si.s[1] = 0x0403; /* |00000100|00000011| */ 38 printf("Before swap: %d\n", si.i); 39 byteSwap(si.i, &i); 40 printf("After swap: %d\n", i); 41 } /* driver */ [pluto:~] byteSwap Before swap: 67305985 After swap: 16909060