基本原理是将LONG型分为byte组(需要注意字节顺序,即:big endian和 little endian),然后通过fwrite将数组按照顺序写入到文件中。读取LONG型时,fread每个字节,并对字节进行移位操作,组成LONG型。这里应该称为数据处理,应该不算做压缩处理。
基本代码(来自swish-e 2.4.5)为:
unsigned long PACKLONG(unsigned long num) { unsigned long temp = 0L; unsigned char* s; int sz_long = sizeof(unsigned long); if(num && LITTLE_ENDIAN) { s = (unsigned char*) &temp; while(sz_long) *s++ = (unsigned char*) ((num >> ((--sz_long) << 3)) & 0xFF); return temp; } return num; }
需要注意的是,如果机器是Little endian(the first read byte is the biggest),首先读取的字节为最低位,需要将字节顺序逆序。先将LONG型中的高位byte放在第一个unsigned char中。
将LONG长整型变化以后,通过printlong将LONG型写入到文件中,基本代码为中:
void printlong(FILE* fp, unsigned long num) { if (fwrite(&num, sizeof(unsigned long), 1, fp) != 1) { fprintf(stderr, "write long error!"); exit(1); } }
LONG型的读取和恢复。
首先从文件中读取LONG型的数据,此时为处理以后的数据,还需要恢复。
unsigned long readlong(FILE* fp) { unsigned long num; fread(&num, sizeof(unsigned long), 1, fp); return num; }
然后恢复读取的LONG型数据为正确的格式,基本代码(swish-e2.4.5)为:
unsigned long UNPACKLONG(unsigned long num) { unsigned long temp = 0L; unsigned char* s = (unsigned char*) # int sz_long = sizeof(unsigned long); if (num && LITTLE_ENDIAN) { while(sz_long) temp += *s++ << ((--sz_long) << 3); return temp; } return num; }
如果是Little endian,则将先读取的byte数据,右移sz_long * 8位,最后组成正确的LONG型数据。
通过以上处理,可以讲LONG型数据变换处理以后,通过bianry文件的方式进行存取。