Wrapping every expression with % 2 ** 32 to get a C-like behavior I'm trying to port the following C loop to Python:

for (int32_t i = 32; --i &gt;= 0;) {
    v0 += ((v1 &lt;&lt; 4 ^ v1 &gt;&gt; 5) + v1) ^ (sum + k[sum &amp; 3]);
    sum -= delta;
    v1 += ((v0 &lt;&lt; 4 ^ v0 &gt;&gt; 5) + v0) ^ (sum + k[sum &gt;&gt; 11 &amp; 3]);
}


The problem is that the these integers are 32-bit unsigned and the code above relies on integer wrapping. My first attempt was to introduce the U32 class (see here), but after porting this code to Python 3, the solution got so ugly (see here) that I started to looking for other ones. My best idea at the moment is to wrap every expression with % 2 ** 32, so that it wraps around. Here's how this looks:

for _ in range(32):
    v0 = (
        v0
        +
        (
            (
                (v1 &lt;&lt; 4) % 2**32 ^ (v1 &gt;&gt; 5) % 2**32
            ) % 2**32
            +
            v1 ^ (sum_ + k[sum_ &amp; 3]) % 2**32
        ) % 2**32
    ) % 2**32

    sum_ = (sum_ - delta) % 2 ** 32

    v1 = (
        v1
        +
        (
            (
                (
                    (v0 &lt;&lt; 4) % 2**32 ^ (v0 &gt;&gt; 5) % 2**32
                ) % 2**32 + v0
            ) % 2**32
            ^
            (sum_ + k[(sum_ &gt;&gt; 11) % 2**32 &amp; 3]) % 2**32
        ) % 2**32
    ) % 2**32


It looks strange and I'm not sure it's the best idea. What do you think of it?  Is it something that needs improving?  If so, how?
Firstly, the expensive modulo operation % 2**32 can be replaced by a cheap bitwise and: &amp; 2**32-1. Make sure to familiarize yourself with operator precedence, because it's not intuitive when it comes to bitwise operators (if you haven't done that yet).

As a next step, you could use the following properties to optimize the equations:


(a % m + b % m) % m = (a + b) % m
(a &amp; n ^ b &amp; n) &amp; n = (a ^ b) &amp; n


That allows you get rid of many of the &amp; 2**32-1 operations at the cost of bigger intermediate results.  If you want to make sure to get the highest speed, do some perfs. In any case, it will make the code much more readable.