Checksum软件的简单设计

时间:2023-03-09 03:00:11
Checksum软件的简单设计

相信大家平时在测试一些bin文件的时候,经常都会要求计算checksum值,其实就是校验和,非常的简单,比如下图这个软件:

Checksum软件的简单设计

我传入一个.bin文件,读出来的Checksum值就是0x0AD8B8。

那么,我如何用C语言终端来实现这个简单的软件做测试工作呢?

请看源码:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    int fd ;
    int i ;
    unsigned int buffer[6680] = {0};
    unsigned int one , two , three , four ;
    unsigned int checksum = 0 ;
    fd = open("Midi_001.bin",O_RDONLY);
    if(-1 == fd){
        printf("打开文件失败!\n");
        return -1 ;
    }
    lseek(fd , 0 , SEEK_SET);
    read(fd , buffer , 6680);
    for(i = 0 ; i < 6680 / 4  ; i++)
    {
        one = buffer[i] & 0xff ;
        two = (buffer[i] & 0xff00) >> 8 ;
        three = (buffer[i] & 0xff0000) >> 16 ;
        four = (buffer[i] & 0xff000000) >> 24 ;
        checksum += one + two + three + four ;
    }
    printf("%d---->0x0%x\n",checksum,checksum);
    return 0;
}

运行结果:

Checksum软件的简单设计

运行结果和软件结果是一样的,那么这个简单的checksum软件就算设计成功了。

但是咱们考虑一个问题,如果,我要读更大bin文件呢?不止是6K,7K,可能是100M,500M,甚至更大呢?

这点留给大家思考下。

相关文章