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";
In reply to keeping binary data raw by downer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |