>백엔드 개발 >파이썬 튜토리얼 >如何理解这段校验和算法 Python 代码?

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

WBOY
WBOY원래의
2016-06-06 16:23:321570검색

回复内容:

这段代码我可以跟你解释,是个经典代码了,刚好我也刚看过,我这是长这个样子的:
<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>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.