对于目标机是大端字节序的机器,进行字节码的转换,提供了16byte、32byte、64byte字节的转换。在intset\ziplist\zipmap三种数据结构中使用,使得不同字节序机器生成的rdb文件格式都是统一的(小端字节序),便于兼容。
代码实在是太简单了,贴上来,不多说了。
endian.h
1 #ifndef __ENDIAN_H 2 #define __ENDIAN_H 3 4 void memrev16(void *p); 5 void memrev32(void *p); 6 void memrev64(void *p); 7 8 /* variants of the function doing the actual convertion only if the target 9 * host is big endian */ 10 #if (BYTE_ORDER == LITTLE_ENDIAN) 11 #define memrev16ifbe(p) 12 #define memrev32ifbe(p) 13 #define memrev64ifbe(p) 14 #else 15 #define memrev16ifbe(p) memrev16(p) 16 #define memrev32ifbe(p) memrev32(p) 17 #define memrev64ifbe(p) memrev64(p) 18 #endif 19 20 #endif
endian.c
1 /* Toggle the 16 bit unsigned integer pointed by *p from little endian to 2 * big endian */ 3 void memrev16(void *p) { 4 unsigned char *x = p, t; 5 6 t = x[0]; 7 x[0] = x[1]; 8 x[1] = t; 9 } 10 11 /* Toggle the 32 bit unsigned integer pointed by *p from little endian to 12 * big endian */ 13 void memrev32(void *p) { 14 unsigned char *x = p, t; 15 16 t = x[0]; 17 x[0] = x[3]; 18 x[3] = t; 19 t = x[1]; 20 x[1] = x[2]; 21 x[2] = t; 22 } 23 24 /* Toggle the 64 bit unsigned integer pointed by *p from little endian to 25 * big endian */ 26 void memrev64(void *p) { 27 unsigned char *x = p, t; 28 29 t = x[0]; 30 x[0] = x[7]; 31 x[7] = t; 32 t = x[1]; 33 x[1] = x[6]; 34 x[6] = t; 35 t = x[2]; 36 x[2] = x[5]; 37 x[5] = t; 38 t = x[3]; 39 x[3] = x[4]; 40 x[4] = t; 41 } 42 43 #ifdef TESTMAIN 44 #include <stdio.h> 45 46 int main(void) { 47 char buf[32]; 48 49 sprintf(buf,"ciaoroma"); 50 memrev16(buf); 51 printf("%s\n", buf); 52 53 sprintf(buf,"ciaoroma"); 54 memrev32(buf); 55 printf("%s\n", buf); 56 57 sprintf(buf,"ciaoroma"); 58 memrev64(buf); 59 printf("%s\n", buf); 60 61 return 0; 62 } 63 #endif