Home >Backend Development >Python Tutorial >如何理解这段校验和算法 Python 代码?

如何理解这段校验和算法 Python 代码?

WBOY
WBOYOriginal
2016-06-06 16:23:321569browse

回复内容:

这段代码我可以跟你解释,是个经典代码了,刚好我也刚看过,我这是长这个样子的:
<code class="language-python"><span class="k">def</span> <span class="nf">checksum</span><span class="p">(</span><span class="n">data</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="o">%</span> <span class="mi">2</span><span class="p">:</span>
        <span class="n">data</span> <span class="o">+=</span> <span class="n">b</span><span class="s">'</span><span class="se">\x00</span><span class="s">'</span>
    <span class="n">s</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s">'H'</span><span class="p">,</span><span class="n">data</span><span class="p">))</span>
    <span class="n">s</span> <span class="o">=</span> <span class="p">(</span><span class="n">s</span> <span class="o">&</span> <span class="mh">0xffff</span><span class="p">)</span> <span class="o">+</span> <span class="p">(</span><span class="n">s</span> <span class="o">>></span> <span class="mi">16</span><span class="p">)</span>
    <span class="n">s</span> <span class="o">+=</span> <span class="p">(</span><span class="n">s</span> <span class="o">>></span> <span class="mi">16</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">_socket</span><span class="o">.</span><span class="n">ntohs</span><span class="p">(</span><span class="o">~</span><span class="n">s</span> <span class="o">&</span> <span class="mh">0xffff</span><span class="p">)</span>
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn