0% found this document useful (0 votes)
96 views

Huffman Coding Source Code

The document describes Huffman encoding and decoding algorithms for data compression. It includes code for a Huffman encoding class that reads a plaintext file, creates a frequency table of characters, builds a Huffman tree from that table, traverses the tree to encode each character, and writes the encoded text and dictionary to files. It also includes code for a Huffman decoding class that loads the dictionary, and decodes an encoded text file back to the original plaintext using the dictionary. The encoding and decoding algorithms are implemented as C++ classes with methods to initialize data structures, build the Huffman tree, encode/decode text, and read/write files for compression and decompression.

Uploaded by

Mashruk Kabir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

Huffman Coding Source Code

The document describes Huffman encoding and decoding algorithms for data compression. It includes code for a Huffman encoding class that reads a plaintext file, creates a frequency table of characters, builds a Huffman tree from that table, traverses the tree to encode each character, and writes the encoded text and dictionary to files. It also includes code for a Huffman decoding class that loads the dictionary, and decodes an encoded text file back to the original plaintext using the dictionary. The encoding and decoding algorithms are implemented as C++ classes with methods to initialize data structures, build the Huffman tree, encode/decode text, and read/write files for compression and decompression.

Uploaded by

Mashruk Kabir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

CEN450 – Cryptography and Network Security Name: Md.

Mashruk Kabir Shafin


Date: 04. 10. 17 ID: 1410809
Assignment - 1
1. The Huffman – Encryption algorithm is given below…
//Comments in the code appear for the cause of code clarification. Written by Mashruk Kabir.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
struct HuffNode{
//A struct which will hold information (via objects) about each unique plaintext character frequency and the character itself
public:
char myChar;
int myFrequency;
HuffNode *myLeft, *myRight;
};
class priorityQueue{
//An Array-Based priority queue which will carry out the operations needed to be done for the compression
int f = 0,r = -1, size, count = 0;
HuffNode** ptr;
//Because a node itself is a pointer referring to an object of class HuffNode, hence the usage of double asterisk. This array is, for all intents and purposes, a 1D object array
public:
void init_q(int);
void prioritize_q();
void enqueue(HuffNode*);
HuffNode* dequeue();
HuffNode* front();
bool check_one_item_remaining();
};
void priorityQueue::init_q(int n){
size = n;
ptr = new HuffNode*[size];
}
void priorityQueue::prioritize_q(){
//The priority of the queue is maintained through a simple insertion sort every time a new node is entered. Stability of the sorting algorithm makes it ideal
for(int j = 1;j < count; j++){
HuffNode* key = ptr[j];
int i = j-1;
while(i>=0 && ptr[i]->myFrequency > key->myFrequency){
ptr[i+1]=ptr[i];
i--;
}
ptr[i+1] = key;
}
}
void priorityQueue::enqueue(HuffNode* n){
ptr[++r] = n;
count++;
prioritize_q();
}
HuffNode* priorityQueue::dequeue(){
//Because Array Size is remaining the same throughout each dequeueing requires left shifting the objects upto the recent-most element
HuffNode* aux;
aux=ptr[f];
for(int i=0;i<r;i++){
ptr[i]=ptr[i+1];
}
count--;
r--;
return aux;
}
HuffNode* priorityQueue::front(){
return ptr[f];
}
bool priorityQueue::check_one_item_remaining(){
if(count>1) return true;
else false;
}
class HuffCode{
//A class to implement Compression Algorithm efficiently
int **ptr,length,str_count = 0;
string **ptr2,file;
priorityQueue myQueue;
public:
//Local function prototypes
void init_arr();
void init_arr2();
void read_file(string);
void create_q();
void create_BT();
void encoding(HuffNode*,string);
void compressed_text();
};
void HuffCode::init_arr(){
//This 2D array will store each character(ascii format) and their frequency as they appear in the plaintext
ptr=new int*[length];
for(int i=0;i<length;i++){
ptr[i]=new int[2];
}
//Initialization
for(int i=0;i<length;i++){
ptr[i][0]=-1;
ptr[i][1]=0;
}
}

1
void HuffCode::init_arr2(){
//This 2D string array would store the encoded text for each character as they appear in the plaintext, essentially the dictionary
ptr2=new string*[length];
for(int i=0;i<length;i++){
ptr2[i]=new string[2];
}
}
void HuffCode::read_file(string s){
//This function is responsible for creating the character frequency table (ascii) from the characters in the Plaintext file
string sentence = "", str="";
int counter = 0, check = 0, temp;
validation:
ifstream fin(s.c_str());
if(fin.is_open()){
if(fin.good()){
while(fin.eof()==false){
getline(fin,str,'\n');
sentence=sentence+str+'\n';
}
sentence.erase(sentence.size()-1);
length=sentence.size();
file=sentence;
init_arr();
for(int i=0;i<length;i++){
for(int j=0;j<=counter;j++){
temp = sentence[i];
if(ptr[j][0]==temp){
ptr[j][1]++;
check++;
}
}
if(check==0){
ptr[counter][0]=temp;
ptr[counter++][1]=1;
}
check=0;
}
}
}
else{
cout<<"(!)The file name you entered is non-existent. Please enter a valid file name: ";
getline(cin, s);
goto validation;
}
fin.close();
length=counter;
}
void HuffCode::create_q(){
//This function is responsible for creating and enqueuing objects into the array containing Plaintext characters character and their frequency
char c;
myQueue.init_q(length);
for(int i=0;i<length;i++){
HuffNode* Node=new HuffNode;
c=ptr[i][0];
Node->myChar=c;
Node->myFrequency=ptr[i][1];
Node->myLeft=NULL;
Node->myRight=NULL;
myQueue.enqueue(Node);
}
}
void HuffCode::create_BT(){
//Two elements are dequeued from every iteration and a new object is created such that its value(frequency) is the sum of the two objects and its left-leaf is first dequeued object
//and right-leaf is second dequeued object. Priority is maintained at enqueueing. This continues until there is only one object in the queue, namely the root of the BT.
while(myQueue.check_one_item_remaining()){
HuffNode *Node,*left,*right;
Node=new HuffNode;
left=myQueue.dequeue();
right=myQueue.dequeue();
Node->myFrequency=left->myFrequency + right->myFrequency;
Node->myLeft=left;
Node->myRight=right;
myQueue.enqueue(Node);
}
init_arr2();
string a = "";
encoding(myQueue.front(), a);
}
void HuffCode::encoding(HuffNode* n,string aux){
//Responsible for traversing the tree and figuring out the encoded text for each character by the order of the direction traversed for each character.
//"0" will be added to the encoded text for the character if traversed left, "1" if traversed right
if(n!=NULL){
if(n->myLeft!=NULL){
encoding(n->myLeft,aux+'0');
}
if(n->myLeft==NULL&&n->myRight==NULL){
ptr2[str_count][0]=n->myChar;
ptr2[str_count][1]=aux;
aux="";
str_count++;
}
if(n->myRight!=NULL){
encoding(n->myRight,aux+'1');
}
}
}

2
void HuffCode::compressed_text(){
//Responsible for writing the encoded text file by replacing each character in the Plaintext with their encoded text
//Also creates the dictionary file
string str;
int temp;
cout<<"\nCongratulations! Text within the file has been Compressed! Enter the name of Encoded-text File to be saved: ";
getline(cin,str);
ofstream fout(str.c_str());
int s;
s=file.size();
for(int i=0;i<s;i++){
for(int j=0;j<length;j++){
if(ptr2[j][0][0]==file[i]) fout<<ptr2[j][1];
}
}
fout.close();
cout<<"\nCompressed text file saved!\n\n";
//Now to save the Dictionary File. Ascii Encoded.
ofstream fdict("Dictionary.txt");
for(int j=0;j<length;j++){
temp = ptr2[j][0][0];
fdict<<temp<<" "<<ptr2[j][1];
if(j < length-1) fdict<<endl;
}
cout<<"Dictionary Saved!\n";
}
int main(){
HuffCode a;
string f = "";
cout<<" ********************************************************************************************************* "<<endl;
cout<<" Huffman Encoder"<<endl;
cout<<" ********************************************************************************************************* "<<endl;
cout<<"\nEnter the name of the Plaintext file: ";
getline(cin,f);
a.read_file(f);
a.create_q();
a.create_BT();
a.compressed_text();
return 0;
}

2. The Huffman – Decryption algorithm is given below…


//Comments in the code appear for the cause of code clarification. Written by Mashruk Kabir.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
class HuffDeCode{
int length;
string **ptr;
public:
void init_arr(int);
void load_dict();
void decompress(string);
};
void HuffDeCode::init_arr(int l){
//This 2D string array would store the encoded text for each character as they appear in the plaintext, essentially the dictionary
length = l;
ptr = new string*[length];
for(int i=0;i<length;i++){
ptr[i] = new string[2];
}
}
void HuffDeCode::load_dict(){
//Loading Dictionary into program
string str="";
int counter = 0;
ifstream fin("Dictionary.txt");
if(fin.is_open()){
if(fin.good()){
while(fin.eof()==false){
getline(fin,str,'\n');
counter++;
}
init_arr(counter);
}
}
else{
cout<<"(!)Dictionary file not found! Decoding Terminated!";
exit(1);
}
fin.close();
str = "";
counter = 0;
int temp;
string aux;
ifstream fdict("Dictionary.txt");
while(fdict.eof()==false){
getline(fdict,str,'\n');
int j = 0;

3
for(int i = 0;i < str.size(); i++){
if(str[i]==' '){
temp = atoi((str.substr(0,i)).c_str());
ptr[counter][0] = temp;
ptr[counter][1] = str.substr(i+1,str.size()-(i+1));
break;
}
}
counter++;
}
}
void HuffDeCode::decompress(string s){
//This function is responsible for decoding the encrypted text file with the dictionary provided
string str, decoded;
validation:
ifstream fin(s.c_str());
if(fin.is_open()){
if(fin.good()){
load_dict();
getline(fin,str,'\n');
cout<<"\nEnter the name of the Decoded file to be saved: ";
getline(cin,decoded);
ofstream fout(decoded.c_str());
string aux = "";
for(int i = 0;i < str.size(); i++){
aux += str[i];
for(int j = 0;j < length; j++){
if(ptr[j][1] == aux){
fout << ptr[j][0];
aux = "";
break;
}
}
}
}
}
else{
cout<<"(!)The file name you entered is non-existent. Please enter a valid file name: ";
getline(cin, s);
goto validation;
}
fin.close();
cout<<"\nFile decrypted!";
}
int main(){
HuffDeCode a;
string f = "";
char c;
cout<<" ********************************************************************************************************* "<<endl;
cout<<" Huffman Decoder"<<endl;
cout<<" ********************************************************************************************************* "<<endl;
cout<<"\nEnter Encoded text File name: ";
getline(cin,f);
a.decompress(f);
return 0;
}

You might also like