2017-08-01 22 views
-4

我的程序读取一个文件,通过将文件处理为四个字节的整数并对每个块进行求和,然后将其与预先计算的校验和进行比较以检查文件的有效性,从而计算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; 
    } 
+5

魔术会发生。不,实际上它不能。你的代码在哪里? –

+3

'a = 10; b = 16; printf(“%u%x \ n”,a,b);' - 至少他们打印相同。 – chux

+3

这可能是因为这两个数字实际上是不同的。这可能是因为你使用了不恰当的技术(可能是'%d')打印出来的,这些技术无意中使它们看起来一模一样。这可能是因为在你印刷他们的时间之间改变了他们,并对他们进行了比较。你为什么不告诉我们你的代码,所以我们不必疯狂猜测? –

回答

0

我定义我的校验和变量unsigned long int类型,因为这是通过typedef作为图书馆uint4我移植(其中,此代码的基础来自)。结果表明库仅用于32位体系结构,所以unsigned long int是4字节,而在我的机器上(64位)则是8字节。将变量更改为unsigned int固定了所有内容,但我需要做很多工作,将库从32位移植到64位。

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

相关问题