大牛们,这段 Python 校验和算法代码怎么理解呢??

2016-06-02 15:51:37 +08:00
 BeginMan

这是我在看《 Python 网络编程攻略》第 3.2 纯 Python 实现 Ping 程序代码,其中关于校验和算法部分代码看的吃力。代码如下:

def do_checksum(self, source_string):
    """  Verify the packet integritity """
    sum = 0
    max_count = (len(source_string)/2)*2
    count = 0
    while count < max_count:
        val = ord(source_string[count + 1])*256 + ord(source_string[count])
        sum = sum + val
        sum = sum & 0xffffffff 
        count = count + 2
 
    if max_count<len(source_string):
        sum = sum + ord(source_string[len(source_string) - 1])
        sum = sum & 0xffffffff 
 
    sum = (sum >> 16)  +  (sum & 0xffff)
    sum = sum + (sum >> 16)
    answer = ~sum
    answer = answer & 0xffff
    answer = answer >> 8 | (answer << 8 & 0xff00)
    return answer

不太明白的地方在:

  1. while 循环这段
  2. 还有就是将高 16bit 与低 16bit 反复相加这部分

大牛啊,请赐教!

2301 次点击
所在节点    问与答
3 条回复
mengzhuo
2016-06-02 16:19:01 +08:00
CRC32?
fcicq
2016-06-02 17:27:25 +08:00
RFC 1071 吧
mengzhuo
2016-06-02 18:49:10 +08:00
ls 正解

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/283003

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX