Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
huffmanCoding/Huffman.cpp
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
80 lines (68 sloc)
1.78 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Huffman.H" | |
#include <iostream> | |
void Huffman::generateBitMapHelper(std::shared_ptr<Node> curr, std::string bin){ | |
if(curr->isLeaf()){ | |
_bitMap[curr->letter] = bin; | |
} | |
else{ | |
generateBitMapHelper(curr->left,bin+"0"); | |
generateBitMapHelper(curr->right,bin+"1"); | |
} | |
} | |
void Huffman::generateBitMap(){ //Wrapper class to recursively call enumerateTreeHelper with DFS | |
generateBitMapHelper(_tree,""); | |
} | |
void Huffman::printBitMap(){ | |
cout << "MAP TABLE BEGIN\n" << endl; | |
for (auto it = _bitMap.begin();it != _bitMap.end();it++){ | |
cout << it->first << " : " << it->second << endl; | |
} | |
cout << "MAP TABLE END\n" << endl; | |
} | |
string convertToBits(string uncompressed){ //Converts the string format bits into char | |
string compressed = ""; | |
int index = 0; | |
char comp; | |
for (char c : uncompressed){ | |
if (!index){ | |
comp = 0x0; | |
} | |
comp = comp | atoi(&c); | |
if (index == 7){ | |
compressed += comp; | |
} | |
else{ | |
comp = comp << 1; // Shift over one bit | |
} | |
index = (index + 1) % 8; | |
} | |
if(index){ // If body is not a multiple of 8, then the last few bits need to be copied into compressed | |
comp = comp << (7-index); | |
compressed += comp; | |
} | |
return compressed; | |
} | |
string convertToString(string compressed){//converts from binary form to string form. | |
string total = ""; | |
for (char c : compressed){ | |
string tmp = ""; | |
for (int i = 0; i < 8;i++){ | |
tmp = to_string(c & 0x1) + tmp; | |
c = c >> 1; | |
} | |
total += tmp; | |
} | |
return total; | |
} | |
template <class Ptr> | |
string preOrder(Ptr curr, string & letters){ | |
if (curr->isLeaf()){ | |
letters += string(1,curr->letter); | |
return "1"; | |
} | |
return "0" + preOrder(curr->left,letters) + preOrder(curr->right,letters); | |
} | |
void Huffman::printPreorder(){ | |
string letts = ""; | |
cout << preOrder(_tree,letts) << endl; | |
} |