【问题标题】:Why doesn't my code return the checksum I am expecting and I pre-calculated?为什么我的代码没有返回我期望的和我预先计算的校验和?
【发布时间】:2017-08-01 17:21:30
【问题描述】:

我的程序读取一个文件,通过将文件处理为 4 字节整数并对每个块求和来计算 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; 
    }

【问题讨论】:

  • 魔法会发生。不,实际上它不能。你的代码在哪里?
  • a=10; b = 16; printf("%u %x\n", a,b); - 至少它们的打印相同。
  • 这可能是因为这两个数字实际上不同。可能是因为您使用不正确的技术(可能是%d)打印它们,无意中使它们看起来相同。这可能是因为在您打印它们并比较它们之间发生了一些变化。你为什么不给我们看你的代码,这样我们就不用胡乱猜测了?
  • 原帖已更新

标签: c checksum


【解决方案1】:

我将校验和变量定义为 unsigned long int,因为它在我要移植的库中被定义为 uint4(此代码的基础来自哪里)。事实证明,该库仅用于 32 位架构,因此 unsigned long int 为 4 个字节,而在我的机器(64 位)上为 8 个字节。将变量更改为 unsigned int 可以解决所有问题,但我需要做很多工作将库从 32 位移植到 64 位。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 2019-12-30
    相关资源
    最近更新 更多