Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Normally in a language like C, we would expect overflow, because the checksum itself is only one byte. I'm not sure about the internals of python, but from my experience with the language it looks like it will default to a larger size variable (maybe some internal bigInt class or something). Is there anyway to mimic the expected behavior of adding two chars, without writing my own implementation? Thanks.


2 Answers

Sure, just take the modulus of your result to fit it back in the size you want. You can do the modulus 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
like image 66
Kiv Avatar answered Oct 29 '25 05:10

Kiv


to improve upon the earlier example, just bitwise-and it with 0xFF. not sure if python does the optimization by default or not.

sum(bytes) & 0xFF
like image 38
nategood Avatar answered Oct 29 '25 05:10

nategood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!