-2

I am new to python and want to change one code in C to python. Can someone guide me please. This is as a checksum code.

unit16_t CheckSum1ByteIn2ByteOut(unit8_t* data, int len)
{
    unit16_t checksum = 0;
    ASSERT(Null != data);
    for(int i = 0;i < len; i++)
    {
        checksum +=data[i];
    }
    checksum = ~checksum;
    return checksum;
}
mch
  • 9,424
  • 2
  • 28
  • 42
mechbaral
  • 103
  • 7
  • 3
    The Python code will look almost exactly the same so I suggest you try yourself first... – thebjorn May 23 '19 at 10:56
  • Thank you for your reply, I could not do this as i don't know the relative function for Nor(bitwise operation) and when I tried to add HEX and do it myself I could not get the result. Please refer me some reference/document so that I can achieve this, Thank you :) – mechbaral May 23 '19 at 11:09
  • If the bitwise not is your only problem https://stackoverflow.com/q/31151107/3684343 will be a duplicate. – mch May 23 '19 at 11:13
  • 1
    @mechbaral: There is no NOR in there, but bitwise invert is the same operator (`~`). You will need to mask after it to force it back to a 16 bit unsigned integer, that's all. – ShadowRanger May 23 '19 at 11:13
  • @thebjorn does mine look almost exactly the same? – Antti Haapala -- Слава Україні May 23 '19 at 11:50
  • @AnttiHaapala the C-version is a sum and a twiddle, so yes. That you chose to write the for-loop as a call to the `sum()` function is just an optimization - the OP _could_ have written it almost line-for-line equivalent (ie. just presenting C code and ask for a Python translation makes this a pretty weak question). – thebjorn May 23 '19 at 12:36
  • Side-note: Did you retype the C code by hand? Or put it though a spellchecker or something? Because `unit16_t` and `unit8_t` aren't standard types, nor is `Null` a standard constant. – ShadowRanger May 23 '19 at 14:40
  • @ShadowRanger I retyped the code so may be there is some error when I was typing – mechbaral May 25 '19 at 04:36
  • @thebjorn what you said is true its more like a asking for a translation but I could not do the translation myself and didnt know where to look for learning that too. Actually I tried to do the conversion but I got stuck when I tried to add the hex values like 5A+A5+01+3D+20+55+7C+7C+54+FE. Nevertheless you guys have helped me one more step, Thank you :D – mechbaral May 25 '19 at 04:39

1 Answers1

2

Given Python 3 and data as bytes, you can get the integer sum of unsigned bytes as sum(data). The result is not 16-bit but unlimited precision integer. You can then invert this - which will result unlimited precision one's complement of the sum, which will be a negative integer, and then clamp to 16 bits with binary AND. Given that the code is

def checksum(data: bytes) -> int:
    return (~sum(data)) & 0xFFFF