downer has asked for the wisdom of the Perl Monks concerning the following question:
this line in my perl gives surprising results:#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct vbyte_record{ unsigned char* vbyte_result; short vbyte_len; } oneRecord; void displayBits(unsigned char*, int); oneRecord vbyte_compress(int); /*display bits of an unsigned char value*/ void displayBits(unsigned char* value, int len){ int shift = 7; unsigned char mask = '1' << shift; unsigned i, j; for(j=0; j<len; j++){ for(i=1; i<=8; i++){ printf("%c", value[j] & mask ? '1': '0'); value[j] <<= 1; } } return; } /* compress an integer into vbyte; first check how many bytes this integer needs; then set the highest bit of all byte to 1 except the lowest byte; encode each byte respectively */ oneRecord vbyte_compress(int number){ short index = (short) floor(log10(number)/log10(128)); //number of +bytes needed unsigned char* result; short i; int remainder = number; div_t temp; unsigned char mask = (char) 1 << 7; //used to set highest bit to 1 oneRecord record; result = (unsigned char*) malloc(sizeof(char)*(index+1)); /* if there are more than one byte; encode the higher byte */ if(index > 0){ for(i=index; i>=1; i--){ temp = div(remainder, (int)pow(128, i)); result[index-i] = (char) temp.quot | mask; remainder = temp.rem; } } /*encode the lowest byte*/ result[index] = (char) remainder; record.vbyte_result = result; record.vbyte_len = index+1; return record; } char* varbyte(int number) { oneRecord record; int decom_num; record = vbyte_compress(number); return record.vbyte_result; }
$compressed.= varbyte($x); print "$x: ",length($x)," compressed ",length($compressed), "\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: keeping binary data raw (char*)
by tye (Sage) on Oct 26, 2007 at 15:15 UTC | |
by syphilis (Archbishop) on Oct 26, 2007 at 16:32 UTC | |
by tye (Sage) on Oct 26, 2007 at 18:25 UTC | |
by downer (Monk) on Oct 29, 2007 at 18:59 UTC | |
|
Re: keeping binary data raw
by ikegami (Patriarch) on Oct 26, 2007 at 15:14 UTC | |
|
Re: keeping binary data raw
by syphilis (Archbishop) on Oct 26, 2007 at 15:49 UTC | |
by downer (Monk) on Oct 26, 2007 at 16:20 UTC | |
by ikegami (Patriarch) on Oct 26, 2007 at 16:49 UTC | |
by downer (Monk) on Oct 26, 2007 at 16:53 UTC | |
by ikegami (Patriarch) on Oct 26, 2007 at 16:57 UTC | |
|
Re: keeping binary data raw
by polettix (Vicar) on Oct 26, 2007 at 15:18 UTC |