-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;
}
魔术会发生。不,实际上它不能。你的代码在哪里? –
'a = 10; b = 16; printf(“%u%x \ n”,a,b);' - 至少他们打印相同。 – chux
这可能是因为这两个数字实际上是不同的。这可能是因为你使用了不恰当的技术(可能是'%d')打印出来的,这些技术无意中使它们看起来一模一样。这可能是因为在你印刷他们的时间之间改变了他们,并对他们进行了比较。你为什么不告诉我们你的代码,所以我们不必疯狂猜测? –