I open a file in C and perform a CRC32 algorithm on the data. From this I get a checksum which I now want to append to the file so that the bit-code of the int is at the end of the bitcode of the file. But when I write the integer to the file all numbers are interpreted as chars and not the bitcode of the int is written. So I tried this:
int r, tmp, sum3;
for(r = 0; r < 25; r+=8){
int s;
sum3 = 0;
for(s = r; s < r+8; s++){
tmp = 1;
int v;
if(binzahl2[s] == '1'){ //binzahl2 contains the bitcode of the checksum as char array
for(v = 7; v > s-r; v--)
tmp*=2;
sum3 += tmp;
}
}
int y=fprintf(file, "%c", (char) sum3);
}
But of course every time sum3 is greater than 127 there's a problem with the cast to char so that as first digit of the byte is written 0 and not 1.
Is there any way to fix this so that the 1 is written at the beginning of the byte? Or is there (hopefully) a better way to append the right binary data?
fprintf
is for outputting formatted data (that's what the f at the end stands for). You want to use fwrite
instead.
fseek(file, 0, SEEK_END);
fwrite("\n", sizeof(char), 1, file);
char binzahl2[33];
unsinged int checkSum; //some value you have calculated
unsinged int b = 1;
for(i = 31; i > -1 ; i--){
if( checkSum & (b << i) ){binzahl2[31 - i] = '1';}
else{binzahl2[31 - i] = '0';}
}
binzahl2[32] = 0;
size_t charCount = strlen(binzahl2);
fwrite(binzahl2, sizeof(char), charCount, file);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.