0

Here is HEX string: 57 F1 0F 9A A8 B7 00 08 0B 19 10 00 00 00 00 00 11 0B 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

A8 and B7 is a checksum that i need to calculate

In C it calculated like that (100% worked):

void ByteStream_ComputeCS(void)
{
       int i;
       DWORD cs = 0;
       for (i = 0; i < ByteStream[2] + 3; i++)
       {
               if (i != 2) cs += *((WORD*)ByteStream + i);
       }
       cs = (cs & 0xFFFF) + (cs >> 16);
       ByteStream[4] = (BYTE)cs;
       ByteStream[5] = (BYTE)(cs >> 8);
}

Im trying to do it like that:

data = bytearray.fromhex('57 F1 0F 9A 00 00 00 08 0B 19 10 00 00 00 00 00 11 0B 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00')

c_sum = sum(data)

I just replace checksum with 0 - in C its just dont sum

if (i != 2) cs += *((WORD*)ByteStream + i);

But i get 0x25e. And cant get it to A8 and B7. What I'm doing wrong?

  • 1
    You're doing different things. The C code is a one's complement sum of words (presumably also 16 bit), skipping over the word where the checksum goes, and using a length value in the data. (Looks a bit like a IPv4 checksum.) The Python code is a sum of bytes. You'll want to look into struct or array modules. Also, you never defined for us what DWORD, WORD or BYTE are. Example: `hex(sum(array.array('H',buffer(data))))` – Yann Vernier Nov 29 '17 at 07:59
  • I found my mistake and problem: i sum 57 + F1 + 0F + 9A +...but have to sum 57F1 + 0F9A + .... The solve i found is to convert hex string into bytes this way: def HexToByte(hexStr): bytes = [] hexStr = ''.join(hexStr.split(" ")) for i in range(0, len(hexStr), 4): bytes.append(int(hexStr[i:i + 4], 16)) return bytes And then sum it. But is there any other way? – Павел Кузиков Nov 29 '17 at 08:16
  • I believe a solution can be found here if you have not found one already https://stackoverflow.com/questions/19744391/calculate-hex-checksum-in-python – Dennis Jensen Jul 18 '19 at 15:14

1 Answers1

0

So I understand that i have to sum 57F1 + 0F9A + ...., but with

data = bytearray.fromhex(....)
c_sum = sum(data)

I do it like 57 + F1 + 0F + 9A +..

The way to solve it, that i found:

def HexToByte(hexStr):

    bytes = []

    hexStr = ''.join(hexStr.split(" "))

    for i in range(0, len(hexStr), 4):
        bytes.append(int(hexStr[i:i + 4], 16))

    return bytes

And then sum it. And its ok But is there any other way?