计算16位校验和? [英] Calculating a 16 bit checksum?

查看:977
本文介绍了计算16位校验和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用c中的程序读取文件,然后我必须对程序进行8位和16位校验和。到目前为止,我只完成了8位校验和。



这是我的理解



我读取文件并将信息存储在一个字符数组中,最后它需要换行。因此,例如,要计算8位校验和,本质上就是这样



文件共有3个字母(3个字母和换行符)



因此数组可容纳4个字符aaa +(换行符)(97 + 97 + 97 + 10)



据我所知,我在数组,然后做%256,那是我的校验和。



97 * 3 = // 3从我的理解中从ascii表中拉出一个(小a)



291 + 10 = 301 // +换行符



301%256 = cc以十六进制表示// //



但是我对于如何计算16位校验和感到困惑,因为如果单个字符数组不能一次添加2个字符,那么我将无法添加?



任何帮助将不胜感激

解决方案

要计算16位校验和,请以2为增量处理数组,然后将一个字节放入低字节。

  uint8_t array [MAX] ]; //将数据复制到
size_t长度; //这是数据
uint16_t校验和= 0的长度;
size_t even_length =长度-长度%2; //对于(int i = 0; i< even_length; i + = 2),向下舍入为2
的倍数{
uint16_t val = array [i] + 256 * array [i + 1] ;
校验和+ = val;
}
if(i< length){//最后一个字节,如果它是奇数长度
校验和+ = array [i];
}

不需要模数,因为无符号整数会自动实现模块化算法。 / p>

Working with a program in c that reads in a file and then I have to do both 8 bit and 16 bit checksum for a program.I only have 8 bit checksum done so far.

This is what I understand

I read the file and store the information in an array of characters and at end it takes the newline feed. so for example to calculate 8 bit check sum this is what happens essentially

File has 3 letters total ( 3 a's and a newline feed)

so array holds 4 chars aaa+(newline) (97+97+97+10)

To my understanding I add all the bytes in the array then do % 256 and that is my checksum.

97 * 3 = //3 a's (small a ) pulled from ascii table from what I understand

291 + 10 = 301 // + newline

301 % 256 = cc in hex //

however I am getting confused on how to calculate the 16 bit checksum because I can't add 2 characters at a time if its a single character array?

any help would be greatly appreciated

解决方案

To calculate a 16-bit checksum, you process the array in increments of 2, and put one byte into the low-order byte of the value that you're adding, and the other byte into the high-order byte.

uint8_t array[MAX]; // The data gets copied into here
size_t length; // This is the length of the data
uint16_t checksum = 0;
size_t even_length = length - length%2; // Round down to multiple of 2
for (int i = 0; i < even_length; i += 2) {
    uint16_t val = array[i] + 256 * array[i+1];
    checksum += val;
}
if (i < length) { // Last byte if it's odd length
    checksum += array[i];
}

There's no need to use modulus, since unsigned integers implement modular arithmetic automatically.

这篇关于计算16位校验和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆