代码之家  ›  专栏  ›  技术社区  ›  assemblaj

为什么我的代码不返回预期的和预先计算的校验和?

  •  -4
  • assemblaj  · 技术社区  · 7 年前

    例如,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; 
        }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   assemblaj    7 年前

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