问题
I am using this function for compression of Numbers:
unsigned char *MyCompress(unsigned int num, unsigned char *buffer){
int i = 0;
unsigned int r = num;
unsigned char temp;
unsigned char s[5];
printf("received %d to compress\n", num);
if(!r){
*buffer++ = 0;
return buffer;
}
while (r){
s[i] = r & 127;
r >>= 7;
printf("s[%d]=%d; r=%d\n", i, s[i], r);
i++;
}
while (--i >= 0){
temp = (unsigned char)(s[i] | (i ? 128 : 0));
printf("temp=%d\n", temp);
*buffer++=temp;
}
return buffer;
}
//Now sending to Print this number
unsigned char *abc, *abc2;
abc=(unsigned char *)malloc(10);
abc2=abc;
len=384;
abc = MyCompress(len, abc);
fwrite(abc2, 1, (abc-abc2), fp);
//Output
s[0]=0; r=3;
s[1]=3; r=0
temp=131
temp=0
Now Getting Error While Reading:
unsigned int MyDeCompress(FILE *fp){
unsigned int c;
unsigned int num = 0;
do{
c = (unsigned) fgetc(fp);
printf(Read="%d\n", c);
if (c <= 0) {
printf("c is < 0 in uncompress1()\n");
exit(0);
}
num <<= 7;
num |= c & 127;
printf("uncompress: c = %d num = %d\n", c, num);
if (!num)
break;
}while (c & 128);
printf("Returning %d\n", num);
return num;
}
//Output
Read=131
uncompress: c = 3 num = 3
Returning 3
Why it is Returning 3. How can I get again 384. But other numbers are reading correctly.
update
I want the logic solution of the problem. Not about Memory Leaks or How to Read File or How to Write File. Kindly provide solution to the problem what can be done.
回答1:
You did not actually run the code you posted in the question. Posting code is a good thing, but only if it is the actual code that you ran and are having a problem with, and if you cut and paste it verbatim, directly into the question.
Once I put the Read=
inside the quotes where it belongs, your code does not do what you claim it does. It returns 131 out when you put 131 in. You do not have a problem. Well, at least not with 131.
There are problems with your code, other than strings that have strayed outside of their quotes.
This:
if (c <= 0) {
printf("c is <= 0 in uncompress1()\n");
exit(0);
}
shouldn't be there at all. As was already pointed out, the <
in the <=
is pointless since c
is unsigned, but more importantly, zero is a perfectly valid value to have in your coded data, e.g. whenever the low seven bits of the number are all zeros. The number 128 codes to 129 0.
For the zero case, you should remove the if(!r){
section and simply make the loop do while
instead of while
.
When you're reading from a file, you need to look for end of file and deal with it.
来源:https://stackoverflow.com/questions/26368124/compressing-numbers-reading-error