2

Goodday, I need to port the following C code in Python, but I can't find a good way to do the unsigned char arithmetic that ignores the overflow bits in python, ie. 255+1=0; 255+2=1 etc. The code below is used in a checksum calculation for a protocol that is implemented in C on the Arduino that I need to interface with.

 unsigned char b[length];
 unsigned char c1=0,c2=0,c3=0,c4=0;
 for (i=0; i<length;i++)
 {
  c1+=b[i];
  c2+=c1;
  c3+=c2;
  c4+=c3;
 }

3 Answers 3

3

You may use % 256:

>>> (255 + 1) % 256
0
>>> (255 + 2) % 256
1

With your example, if b is a Python string:

>>> b = "thisisatest"
>>> c1, c2, c3, c4 = 0, 0, 0, 0
>>> for c in b:
...     c1 = (c1 + ord(c)) % 256
...     c2 = (c2 + c1) % 256
...     c3 = (c3 + c2) % 256
...     c4 = (c4 + c3) % 256
... 
>>> c1, c2, c3, c4
... (181, 36, 46, 174)
Sign up to request clarification or add additional context in comments.

2 Comments

The only reason I didn't add this as an answer, is that the use of ord(c) is not good (IMHO) as the data will be raw non-printable data bits on the wire. That is the reason I used unsigned char[] for b. The answer I chose was for generic reasons ;)
ord() will work with "raw non-printable data": ord('\x00') == 0 (\x00 is a null byte).
1

You can also use bitwise AND, which might be clearer. I also like hex notation for this.

255 & 0xff
256 & 0xff
257 & 0xff
-1 & 0xff

1 Comment

I'm upvoting this one, but it should be a shared answer ;)
0

In Python there is no notion of signed/unsigned. If you want to handle overflow, you can simply use modular arithmetic.

(255 + 1) % 256 = 0
(250 + 2) % 256 = 252
(255 + 5) % 256 = 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.