c语言 - 为什么我的代码没有返回我期望的校验和,并且我预先计算了?



我的程序读取一个文件,通过将文件处理为四个字节整数并对每个块求和来计算 4 字节校验和,然后将其与预先计算的校验和进行比较以检查文件的有效性。

例如,hello_world.txt可能包含以下内容。

世界您好

我已经预先计算了校验和,我知道它是0x49f247db,但最后的比较失败了。

这里可能有什么问题?这是我获取 4 字节整数的方式吗?

我试图通过将缓冲区的指针转换为整数指针并使用"++"运算符迭代缓冲区来做到这一点,但它最终会以某种方式跳过字节。

这是我正在使用的代码。

#include <sys/stat.h> 
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main() {
unsigned char  buffer [1024];
unsigned long int        checksum = 0;
FILE                       *fp;
int                         i;
unsigned long int        length;
fp = open ("hello_world.txt", 0, 0);
if (fp == NULL) exit(0);
for (;;)
{
memset (buffer, 0, sizeof(buffer));
/* Read the next chunk of the file */
length = read (fp, &buffer, 1024); 
if (length == 0)
break;
printf("i'm here. %d %s n", length, strerror(errno));
/* We've read a chunk of the file -- all chunks (except the last)
* will be '1024' bytes in length; the last chunk will 
* probably be less than '1024' bytes.
*/
for (i=0; i<length; i+=4)
{
unsigned long int a = (unsigned long int) ((unsigned char)(buffer[i]) << 24 |
(unsigned char)(buffer[i+1]) << 16 |
(unsigned char)(buffer[i+2]) << 8 |
(unsigned char)(buffer[i+3]));
checksum += a; 
}
}
printf("%d, %x n", checksum, checksum);
if (0x49f247db == checksum) printf("CHECKSUM MATCHED");
/* Close the file and return the checksum */
close (fp);
return 0; 
}

我将校验和变量定义为无符号长整型,因为它在我移植的库中被类型化为 uint4(此代码的基础来自此代码(。事实证明,该库仅用于 32 位架构,因此无符号长整型是 4 个字节,而在我的机器(64 位(上是 8 个字节。将变量更改为无符号 int 修复了所有问题,但我需要做很多工作将库从 32 位移植到 64 位。

我也应该使用 %lx 而不是 %x。

最新更新