Simulating int arithmetic with wrap-around

Serhiy Storchaka storchaka at gmail.com
Fri Dec 30 20:11:49 EST 2016


On 31.12.16 02:30, Steve D'Aprano wrote:
> Are you saying that the best way of doing this is this?
>
> (1) convert signed Python ints to unsigned;
>
> (2) perform operation and bitmask;
>
> (3) convert unsigned back to signed.
>
>
> Here's an example. I want to multiply 7*3 using a signed 4-bit int, getting
> 5 as the answer, and 7*4 getting -4 as the answer:
>
>
> py> N = 4
> py> to_signed(N, to_unsigned(N, 7) * to_unsigned(N, 3) & (2**N - 1))
> 5
> py> to_signed(N, to_unsigned(N, 7) * to_unsigned(N, 4) & (2**N - 1))
> -4

Step 1 is not needed. And you can inline to_unsigned() in to_signed(). I 
introduced it just for clearness.

py> to_signed(N, 7 * 3)
5
py> to_signed(N, 7 * 4)
-4




More information about the Python-list mailing list