1 /* 2 * Compress3.cpp 3 * Copyright 1999-2000 Y.Takagi. All Rights Reserved. 4 */ 5 6 //#define DBG_CON_STREAM 7 8 #ifdef DBG_CON_STREAM 9 #include <fstream> 10 using namespace std; 11 #endif 12 13 #include "Compress3.h" 14 15 #define PACK_TYPE 2 16 17 int compress3(unsigned char *pOut, unsigned char *pIn, int n) 18 { 19 int count; 20 int count_byte; 21 unsigned char *pBase; 22 unsigned char *pLast; 23 unsigned char keep; 24 25 count = 0; 26 count_byte = 0; 27 28 keep = ~(*pIn); 29 pLast = pIn + n; 30 31 for (pBase = pIn; (pBase < pLast) && (count_byte < n) ; pBase++) { 32 if (*pBase == keep) { 33 if (count < 0xff + PACK_TYPE) { 34 count++; 35 } else { 36 *pOut++ = keep; 37 *pOut++ = count - PACK_TYPE; 38 count = 1; 39 keep = *pOut++ = *pBase; 40 count_byte += 3; 41 } 42 } else { 43 if (count > 1) { 44 *pOut++ = keep; 45 *pOut++ = count - PACK_TYPE; 46 count_byte += 2; 47 } 48 count = 1; 49 keep = *pOut++ = *pBase; 50 count_byte++; 51 } 52 } 53 54 if (count > 1) { 55 if ((count_byte + 2) < n) { 56 *pOut++ = keep; 57 *pOut++ = count - PACK_TYPE; 58 count_byte += 2; 59 } else { 60 count_byte = n; 61 } 62 } 63 64 return count_byte; 65 } 66 67 #ifdef DBG_CON_STREAM 68 int main(int argc, char **argv) 69 { 70 if (argc < 2) { 71 return -1; 72 } 73 74 ifstream ifs(*++argv, ios::binary | ios::nocreate); 75 if (!ifs) { 76 return -1; 77 } 78 79 ifs.seekg(0, ios::end); 80 long size = ifs.tellg(); 81 ifs.seekg(0, ios::beg); 82 83 unsigned char *pIn = new unsigned char[size]; 84 unsigned char *pOut = new unsigned char[size * 3]; 85 86 ifs.read(pIn, size); 87 88 int cnt = PackBits(pOut, pIn, size); 89 90 ofstream ofs("test.bin", ios::binary); 91 ofs.write(pOut, cnt); 92 93 delete [] pIn; 94 delete [] pOut; 95 96 } 97 #endif 98