#include "huffman.h"
void CompressionSet::printBitCode(int bitCode, int bitLength)
{
int bitSize = BITSIZE(this->bitCompression);
for (int i = bitSize-1; i > (bitSize-1)-bitLength; i--)
{
printf("%d", (bitCode & (0x01 << ((bitSize-1)-i))?1:0));
}
}
void CompressionSet::printStringBitCodes(char *buffer, int size)
{
int i, cValue, totalBitLength = 0, x;
int bitCode, bitLength;
for (i = 0; i < size; i += this->bitCompression)
{
cValue = this->makeCharCode(&buffer[i]);
this->getBitData(cValue, &bitCode, &bitLength);
this->printBitCode(bitCode, bitLength);
totalBitLength += bitLength;
}
if ((x=(totalBitLength % 8)) != 0)
{
// we have remaining bits that we need to print
for (i = 0; i < 8-x; i++)
{
printf("0");
}
}
printf("\n");
}
int CompressionSet::makeCharCode(char *buffer)
{
int charCode = 0, i;
for (i = 0; i < this->bitCompression; i++)
{
charCode |= (*(buffer+i) << (8*i));
}
return charCode;
}
void *CompressionSet::CompressedString(char *buffer, int size)
{
int charCounter = 0, bitCharCounter = 0, bitCodeCounter = 0, c, i, x;
char *swapstring = new char[size];
int bitLength, bitCode;
memset(swapstring, 0, size);
for (i = 0; i < size; i += this->bitCompression)
{
// get a new character id
c = this->makeCharCode(&buffer[i]);
// get a new bitCode from character
this->getBitData(c, &bitCode, &bitLength);
// attempt to print bitcode into character
for (x = 0; x < bitLength; x++)
{
if (bitCharCounter >= 8)
{
// used up all the bits in this char
// move to next bit
charCounter++;
bitCharCounter = 0;
}
swapstring[charCounter] |= (bitCode & (0x1 << x)) << (7-bitCharCounter);
bitCharCounter++;
}
}
return swapstring;
}
int CompressionSet::getBitCode(int charCode)
{
for (int i = 0; i < this->numUniqueChars; i++)
{
if (this->bitCodeList[i].charCode == charCode)
{
return this->bitCodeList[i].bitCode;
}
}
return NULL;
}
int CompressionSet::getBitLength(int charCode)
{
for (int i = 0; i < this->numUniqueChars; i++)
{
if (this->bitCodeList[i].charCode == charCode)
{
return this->bitCodeList[i].bitLength;
}
}
return NULL;
}
int CompressionSet::getBitData(int charCode, int *bitCode, int *bitLength)
{
for (int i = 0; i < this->numUniqueChars; i++)
{
if (this->bitCodeList[i].charCode == charCode)
{
*bitCode = this->bitCodeList[i].bitCode;
*bitLength = this->bitCodeList[i].bitLength;
return 0;
}
}
return -1;
}
int CompressionSet::getTotalBitLength(char *buffer, int size)
{
int i, cValue, totalBitLength = 0;
for (i = 0; i < size; i += this->bitCompression)
{
cValue = this->makeCharCode(&buffer[i]);
totalBitLength += this->getBitLength(cValue);
}
return totalBitLength;
}
void CompressionSet::makeCharset(char *buffer, int size, int bitComp)
{
bitCompression = bitComp;
NodeTree nt(this, buffer, size);
}
CompressionSet::CompressionSet()
{
bitCodeList = NULL;
} Powered by
GeSHi Syntax Highlighting software.
Author of all (other) material unless otherwise specified:
Loren Segal. Copyright 2005.