Hvisage
Hvisage

Reputation: 264

doing unsigned char arithmetic in python

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;
 }

Upvotes: 2

Views: 1659

Answers (3)

Tom Karzes
Tom Karzes

Reputation: 24052

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

Upvotes: 1

Pierre
Pierre

Reputation: 6237

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)

Upvotes: 3

thaweatherman
thaweatherman

Reputation: 1487

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

Upvotes: 0

Related Questions