0

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:

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?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Axel
  • 61
  • 1
  • 3

1 Answers1

0

bytes objects already iterate to ints, so ord doesn't work. Your function will work for bytes (but not str) by removing the ord() call, using c directly.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271