#include<iostream>
#include<stdio.h>
using namespace std;
typedef unsigned char Bit;
class BitStream{
public:
unsigned char* bitstream;
int position;
int start;
BitStream()
{
start = 0;
position = 0;
bitstream = new unsigned char[1000];
for(int i=0;i<1000;i++)bitstream[i]=0;
}
~BitStream()
{
delete[] bitstream;
}
void Add(Bit tmp)
{
int x = position / 8;
int y = 7 - (position % 8);
bitstream[x] = bitstream[x] | (tmp<<y);
position++;
}
Bit Pop()
{
int x = start / 8;
int y = 7 - (start % 8);
start++;
return (bitstream[x]>>y)&0x1;
}
bool IsEnd()
{
return start==position;
}
void Print()
{
int n,h,sb=position;
if(position%8==0)n=position/8;
else n=position/8+1;
for(int i=0;i<n;i++)
{
Bit tmp = bitstream[i];
if(sb>=8)h=0;
else h=8-sb;
for(int j=7;j>=h;j--)
{
int n = (((int)tmp)>>j) &0x1;
printf("%d",n);
}
sb-=8;
printf(" ");
}
printf("\n");
}
};
BitStream* GammaEncode(int numbers[],int length)
{
BitStream* bs = new BitStream();
for(int i=0;i<length;i++)
{
int n = numbers[i];
int count = 31;
if(n==0){cout<<"can not be 0"<<endl;return bs;}
while(!(n&0x80000000)){count--;n=n<<1;}
//长度部分
for(int j=0;j<count;j++)
bs->Add(1);
bs->Add(0);
//偏移部分
for(int j=1;j<=count;j++)
{
Bit tmp = ((n<<j)>>31)&0x1;
bs->Add(tmp);
}
}
return bs;
}
int* GammaDecode(BitStream* bs,int &length)
{
int* a = new int[100];
while(!bs->IsEnd())
{
int count = 0;
while(bs->Pop())count++;
int n=1;
for(int i=0;i<count;i++)
n = (n<<1)|(bs->Pop());
a[length++] = n;
}
return a;
}
int main()
{
int a[] = {1,2,3,4,9,13,24,511,1025};
//int a[] = {9};
BitStream* hehe = GammaEncode(a,9);
hehe->Print();
int length = 0;
int* b;
b=GammaDecode(hehe,length);
for(int i=0;i<length;i++)
cout<<b[i]<<endl;
system("pause");
return 0;
}
现代信息检索作业5——2
最新推荐文章于 2025-06-11 14:42:51 发布
