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:
我在C中打开一个文件并对数据执行CRC32算法。从中我得到一个校验和,现在我想把它附加到文件中,这样int的位码就在文件的位码的末尾。但当我将整数写入文件时,所有数字都被解释为字符,而不是int的位码。所以我试着:
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.
当然,每次sum3大于127时,对char的转换就会有问题所以字节的第一个数字被写成0而不是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?
有什么方法可以把1写在字节的开头吗?或者有更好的方法添加正确的二进制数据吗?
2 个解决方案
#1
0
fprintf
is for outputting formatted data (that's what the f at the end stands for). You want to use fwrite
instead.
fprintf用于输出格式化数据(这是末尾f的含义)。相反,您希望使用fwrite。
#2
0
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);
#1
0
fprintf
is for outputting formatted data (that's what the f at the end stands for). You want to use fwrite
instead.
fprintf用于输出格式化数据(这是末尾f的含义)。相反,您希望使用fwrite。
#2
0
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);