Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. //
  2. //  Compressor.cpp
  3. //  TextCompression
  4. //
  5. //  Created by Viet Nguyen on 12/4/16.
  6. //  Copyright © 2016 Viet Nguyen. All rights reserved.
  7. //
  8.  
  9. #include "Compressor.hpp"
  10. Compressor::Compressor(string filename, string tofile, vector<wchar_t> symbols, vector<string> codes)
  11. {
  12.     fileSourse = filename;
  13.    
  14.     fileTo = tofile;
  15.    
  16.     for(int i = 0; i < symbols.size(); ++ i)
  17.         map.insert(pair<wchar_t, string>(symbols[i], codes[i]));
  18. }
  19.  
  20. vector<bool> Compressor::getBites(wchar_t c)
  21. {
  22.     string code = map[c];
  23.    
  24.     vector<bool> result  = *new vector<bool>;
  25.    
  26.     for(int i = 0 ; i < code.size(); ++i)
  27.         result.push_back( code[i]=='1');
  28.    
  29.     return result;
  30. }
  31.  
  32.  
  33. void Compressor::CompressText()
  34. {
  35.     //Open sourse text file to get text
  36.     setlocale(LC_ALL, "en_US.UTF-8");
  37.     wifstream input (fileSourse);
  38.    
  39. #ifdef PREFER_BOOST
  40.     boost::locale::generator gen;
  41.     std::locale loc = gen("en_US.UTF-8");
  42. #else
  43.     std::locale loc("en_US.UTF-8");
  44. #endif
  45.     input.imbue(loc);
  46.     wcout.imbue(loc);
  47.    
  48.     //Create new file
  49.     ofstream comp;
  50.     comp.open(fileTo + ".haff", ios::out | ios::binary);
  51.    
  52.     comp << map.size(); //Write number of row in table
  53.    
  54.     for(auto i = map.begin() ; i != map.end(); ++i)
  55.     {
  56.         comp << (*i).first << endl;
  57.        
  58.        
  59.         for (int j = 0; j < (*i).second.size(); ++j)
  60.         {
  61.             bool t = (*i).second[j] == '0';
  62.             comp << t;
  63.         }
  64.         comp<<endl;
  65.     }
  66.    
  67.     int count = 0;
  68.     char buffer = 0;
  69.    
  70.     while (!input.eof())
  71.     {
  72.         wchar_t ch = input.get();
  73.        
  74.         vector<bool> bites = getBites(ch);
  75.        
  76.         for(int i = 0; i < bites.size(); ++i)
  77.         {
  78.             buffer = buffer | (bites[i]? 1 : 0)<<(7 - count);
  79.             count++;
  80.            
  81.             if (count == 8)
  82.             {
  83.                 count = 0;
  84.                 comp << buffer;
  85.                 buffer = 0;
  86.             }
  87.         }
  88.     }
  89.    
  90.     input.close();
  91.     comp.close();
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement