Is there a way to add two bytes with overflow in python?

I am using pySerial to read data from a connected device. I want to calculate the checksum of each packet received. The packet is read as a char array, with the actual checksum being the most recent byte at the end of the packet. To calculate the checksum, I would usually sum over the packet payload, and then compare it with the actual checksum.

Usually in a language like C, we expect overflow because the checksum itself is just one byte. I'm not sure about python internals, but in my experience with the language, it looks as if by default a larger size variable will be used (perhaps some kind of inner class bigInt or something else). In any case, to simulate the expected behavior of adding two characters without writing my own implementation? Thanks.

+3
source share
3 answers

Of course, just grab the module of your result to fit its size. You can execute the module at the end or at every step. For example:

>>> payload = [100, 101, 102, 103, 104] # arbitrary sequence of bytes
>>> sum(payload) % 256 # modulo 256 to make the answer fit in a single byte
254 # this would be your checksum
+6
source

, , 0xFF. , python .

sum(bytes) & 0xFF
+2

, , sum(bytes) % 256 ( sum(bytes) & 0xFF), ( ) , , .

, Python, : Python , .

, functools.reduce():

>>> payload = [100, 101, 102, 103, 104] # arbitrary sequence of bytes
# (Python 3 uses functools.reduce() instead of builtin reduce() function)
>>> import functools
>>> functools.reduce(lambda x,y: (x+y)%256, payload)
254
0

Source: https://habr.com/ru/post/1710205/


All Articles