为什么我的代码 return 不是我期望的和预先计算的校验和?

Why doesn't my code return the checksum I am expecting and I pre-calculated?

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

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

hello world

我已经预先计算了校验和,我知道是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; 
    }

我将校验和变量定义为 unsigned long int,因为它在我正在移植的库(此代码的基础来自该库)中被定义为 uint4。事实证明该库仅用于 32 位体系结构,因此 unsigned long int 是 4 个字节,而在我的机器(64 位)上是 8 个字节。将变量更改为 unsigned int 修复了所有问题,但我需要做大量工作将库从 32 位移植到 64 位。

此外,我应该使用 %lx 而不是 %x。