endian.c (697B)
1 #include "endian.h" 2 3 int is_le() { 4 short s = 42; 5 return *((unsigned char*)&s) == 42; 6 } 7 8 // convert unsigned integer to little-endian representation 9 int to_endian(char direction, int l, void *n) { 10 union le un; 11 12 if (l == 1 || is_le() == direction) { 13 return 0; 14 } 15 switch(l) { 16 case sizeof(long long): 17 un.ll = (long long*)n; 18 break; 19 case sizeof(int): 20 un.i = (int*)n; 21 break; 22 case sizeof(short): 23 un.s = (short*)n; 24 break; 25 default: 26 un.c = (char*)n; 27 } 28 flip_endian(l, &un); 29 30 return 0; 31 } 32 33 void flip_endian(int l, union le *n) { 34 int i; 35 char t; 36 char *ne; 37 38 ne = (n->c)+(l-1); 39 for (i = 0; i < l/2; i++) { 40 t = *(n->c+i); 41 *((n->c)+i) = *(ne-i); 42 *(ne-i) = t; 43 } 44 }