#include "huffman.h"
void printBitCode(int bitCode, int bitLength)
{
for (int i = BITSIZE-1; i > (BITSIZE-1)-bitLength; i--)
{
printf("%d", (bitCode & (0x01 << ((BITSIZE-1)-i))?1:0));
}
}
void printStringBitCodes(void *buffer, size_t size)
{
int i, cValue, totalBitLength = 0, x;
int bitCode, bitLength;
for (i = 0; i < size; i += Node::bitCompression)
{
cValue = makeCharCode(&string[i]);
Node::getBitData(cValue, &bitCode, &bitLength);
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 makeCharCode(char *stringBegin)
{
int charCode = 0, i;
for (i = 0; i < Node::bitCompression; i++)
{
charCode |= (*(stringBegin+i) << (8*i));
/* c = MAKESHORT(string[i], string[i+1]); */
}
return charCode;
}
char *CompressedString(char *string)
{
int charCounter = 0, bitCharCounter = 0, bitCodeCounter = 0, c, i, x;
char *swapstring = (char *)malloc(4096);
int bitLength, bitCode, len = (int)strlen(string);
memset(swapstring, 0, 4096);
for (i = 0; i < len; i += Node::bitCompression)
{
// get a new character id
c = makeCharCode(&string[i]);
// get a new bitCode from character
Node::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 getTotalBitLength(char *string)
{
int i, cValue, totalBitLength = 0, len = (int)strlen(string);
for (i = 0; i < len; i += Node::bitCompression)
{
cValue = makeCharCode(&string[i]);
totalBitLength += Node::getBitLength(cValue);
}
return totalBitLength;
} Powered by
GeSHi Syntax Highlighting software.
Author of all (other) material unless otherwise specified:
Loren Segal. Copyright 2005.