I do not know if it is a endianness, and my example is exactly my program's result.
I pack the binary as follows.
int file_pack:
ack(int size, long int value)
{
int i;
int tempint;
for (i=0; i<size; ++i, ++ptr, value = value>>1, sum = sum<<1) {
if (value & 1) sum |= 1;
if (ptr == 8) {
tempbuffer[bufferindex] = (unsigned char)sum;
bufferindex ++;
if(bufferindex == 1024){
if(fwrite(tempbuffer, 1, bufferindex, poutput) < bufferindex)
fatal_pack_unpack("\nPack error.");
/* printf("\nPack a block of data %d." , bufferindex);*/
bufferindex = 0;
}
/* printf(" %x ", tempch);*/
++num_of_packed_bytes;
++temp_num_of_packed_bytes;
sum=0;
ptr=0;
}
}
return i;
}
class file_pack
{
public:
int ptr ;/* how many bits are packed in sum so far */
int sum ; /* packed bits */
unsigned char tempbuffer[1024];
unsigned char tempbuffer[1024];
unsigned int bufferindex;
........
}
class file_unpack
{
public:
int ptr ;/* how many bits are packed in sum so far */
int sum ; /* unpacked bits */
unsigned char tempbuffer[1024];
int countbuffer;
int buffersize;
....
}
file_unpack::file_unpack(FILE *fptr)
{
ptr = 1;
sum = 0;
pinput = fptr;
num_of_unpacked_bytes = 0;
countbuffer = 0;
/*initialize the unpack process*/
if((buffersize = fread(tempbuffer, 1,1024, pinput) )< 1)
fatal_pack_unpack("\nUnpack error.");
/*printf(" %x ", tempch);*/
printf("\nUnpack 2 buffer %d char", buffersize);
sum = (int) tempbuffer[countbuffer];
countbuffer ++;
sum <<= 1;
num_of_unpacked_bytes ++;
}
long file_unpack::unpack(int size)
{
int i;
unsigned long int value = 0;
/* size == -2 means we initialize things */
if (size == -2) {
return((long)0);
}
/* size == -1 means we want to peek at the next bit without */
/* advancing the pointer */
if (size == -1)
return((long)((sum&256)>>8));
for (i=0; i<size; ++i, ++ptr, sum <<= 1) {
if (sum & 256) value |=(unsigned long) (1<<i);
if (ptr == 8) {
if(countbuffer == 1024 || countbuffer == buffersize){
if((buffersize = fread(tempbuffer, 1,1024, pinput) ) < 1)
if(feof(pinput)){
printf("\nRead out all the files.");
exit(1);
}
else
fatal_pack_unpack("\nRead input file error.");
countbuffer = 0;
/* printf("\nUnpack 2 buffer %d char", buffersize);*/
}
if(countbuffer < buffersize)
sum = (int) tempbuffer[countbuffer];
countbuffer ++;
num_of_unpacked_bytes ++;
/*printf(" %x ", tempch);*/
ptr=0;
}
}
return((long)value);
}
Before my error, I have pack some other data longer than 8 bits, they are not wrong, just from this one, error happens.
Why?
Maybe my fault, but I can not find out it.
Thanks
I have forgot that I execute the pack & unpack on the same computer(Dell optiplex).