I need to store integers in range (0-50000000) in binary file and decode them later. To save space I am storing number of bytes required to decode the integer in first 2 bits of first byte i.e 01XXXXXX refers 2 bytes are required to save the number.I was facing issue in the implementation.The number I am getting after decoding is not correct. Here is my sample code -
int main()
{
FILE *input = NULL,
*output = NULL;
output = fopen("sample.bin","wb+");
unsigned int num = 32594; //(this number would come from input file)
char buff_ts[4];
sprintf(buff_ts,"%d",num);
setBitAt(buff_ts, sizeof(buff_ts), 23, 1); // set first two bits
fwrite(buff_ts,1,sizeof(buff_ts),output);
fclose(output);
input = fopen("sample.bin", "rb");
int diff;
char buff[1];
fread(buff,1,1,input);
char buff_copy = buff[0];
int temp = atoi(buff);
int more_bytes_to_read = (temp>>6); // read first 2 bits
buff_copy = buff_copy & ((1<<6)-1); // reset first 2 bits
if(more_bytes_to_read==0) // if no more bytes to read
{
diff = buff_copy;
}
else
{
char extra_buff[more_bytes_to_read];
fread(extra_buff,1,sizeof(extra_buff),input); // read extra bytes
char num_buf[more_bytes_to_read+1];
num_buf[0] = buff_copy; // copy prev read buffer
for(int i=1;i<=more_bytes_to_read;i++)
{
num_buf[i] = extra_buff[i-1];
}
diff = atoi(num_buf);
}
cout<<diff<<endl;
return 0;
}