Heim >Backend-Entwicklung >Python-Tutorial >如何理解这段校验和算法 Python 代码?

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

WBOY
WBOYOriginal
2016-06-06 16:23:321570Durchsuche

回复内容:

这段代码我可以跟你解释,是个经典代码了,刚好我也刚看过,我这是长这个样子的:
<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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn