简体   繁体   English

Python 二补校验和

[英]Python two complement checksum

I am working in script in which I need to calculate the two's complement of certain hex value.我正在编写脚本,我需要计算某些十六进制值的二进制补码。

I took this function from stackoverflow:我从stackoverflow拿了这个function:

def checksum_calc(s):
    sum = 0
    for c in s:
        sum += ord(c)
    sum = -(sum % 256)
    return '%2X' % (sum & 0xFF)

but if I introduced data like:但如果我引入如下数据:

string = '\x00\x03\x03\xFF'

is correct but if I introduced it like this:是正确的,但如果我这样介绍它:

string = b'\x00\x03\x03\xFF'

I get incorrect checksum.我得到不正确的校验和。

Can you help me with this please?你能帮我解决这个问题吗?

bytes objects already iterate to int s, so ord doesn't work. bytes对象已经迭代到int s,所以ord不起作用。 Your function will work for bytes (but not str ) by removing the ord() call, using c directly.通过直接使用c删除ord()调用,您的 function 将适用于bytes (但不适用于str )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM