关于校验算法的学习(学习以太网时遇到的)以太网的包头还是数据都会有校验,在FPGA上实现IP核时,用的是CRC校验,然后学习ICMP协议时,也看到一种校验算法,以此学习分析一下背后原理。
一、先看看ICMP的包格式,主要是写ping命令是用到(会有一篇专门将ping的c语言实现),所以只是展示与ping命令背后的ICMP规则。
(来自维基)
对于校验的研究暂时不需要理解其他数据的意思,维基对checksum的解释为
Checksum
Error checking data, calculated from the ICMP header and data, with value 0 substituted for this field. The Internet Checksum is used, specified in RFC 1071.
首先校验的是header+data,然后如果忽略补0,规则看RFC 1071,来看看这个文档。
二、在看这个文档之前先了解几个概念:2’s complement 和 1’s complement
其实这就是两种数值的表示方法,
先看2’s complement :这就是我们日常使用的,称为2补码系统。
看看维基大神的解释:
【This system is the most common method of representing signed integers on computers.[2] An N-bit two’s-complement numeral system can represent every integer in the range −(2N − 1) to +(2N − 1 − 1) 】
那怎么编码数据呢,看看:
For example, to find the 4-bit representation of −5 (subscripts denote the base of the representation):
x = 510 therefore x = 01012
Hence, with N = 4:
x* = 2N − x = 24 − 510 = 100002 − 01012 = 10112
The calculation can be done entirely in base 10, converting to base 2 at the end:
x* = 2N − x = 24 − 510 = 1110 = 10112
就是正数是其本身,如5为0101;负数最高位置一,然后将其他低位取反,再加一。
这就是常见的计算机编码方式。
这是编码图
再看看1’s complement
Positive numbers are the same simple, binary system used by two’s complement and sign-magnitude. Negative values are the bit complement of the corresponding positive value. The largest positive value is characterized by the sign (high-order) bit being off (0) and all other bits being on (1). The smallest negat