gpt4 book ai didi

c - 将二进制数据 append 到c中的文件

转载 作者:行者123 更新时间:2023-11-30 17:40:10 29 4
gpt4 key购买 nike

我用 C 打开一个文件并对数据执行 CRC32 算法。由此我得到一个校验和,现在我想将其 append 到文件中,以便 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);
}

但是当然,每次 sum3 大于 127 时,转换为 char 就会出现问题,因此字节的第一个数字会被写入 0 而不是 1。

有没有办法解决这个问题,以便将 1 写入字节的开头?或者是否有(希望)更好的方法来 append 正确的二进制数据?

最佳答案

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);

关于c - 将二进制数据 append 到c中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21609432/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com