I came across a C snippet that performs a nifty modular arithmetic operation using bitwise logic:
int a,b,c;
c = (a + b - 1) & (- b) +b;
The value of c is the smallest multiple of b greater than a+b (edited in response to John Bollinger's answer). I am trying to explain how this works to myself (I have a tenuous understanding of how modular arithmetic and the & operation could be related) but am falling short on insight. On the other hand it looks like I can express it as
c = (a+b) - ((a+b)%b) + (((a+b)%b)?b:0)
This expression is easy to understand. Moreover the appearance of the modular and ? operations suggests that the individual parts can be expressed as bitwise logic and somehow reduced to the expression at the top. But how? I leave it as an exercise if anyone wants to give it a go (this is NOT homework). Implementation need not be in C, and if there is an online ref that explains this you are welcome to provide it but will not be a complete answer. I'd like to see the transition from the bottom to the top expression in clear steps...
Comments This link suggests that this may apply when b is a power of 2. This other link explains that bitwise & does not distribute over addition.
Assume in the expression ...&(-b)
, (-b)
can be replaced with (nums(int)-b)
, where nums(int)
is the total number of possible ints in the representation.
Feel free to specify your favorite compiler/C version.
Sample code:
int a,b,c;
int alow, ahigh;
b = 16;
alow = 8;
ahigh = 20;
printf("a+b c lcm(a+b,b) + ?b \n");
for (a=alow;a<ahigh;a++) {
c = ((a+b-1) & (-b)) +b;
printf("%5d %5d %5d \n",a+b, c, (a+b) - ((a+b)%b) + (((a+b)%b)?b:0) );
}
Sample output:
a+b c lcm(a+b,b) + ?b
24 32 32
25 32 32
26 32 32
27 32 32
28 32 32
29 32 32
30 32 32
31 32 32
32 32 32
33 48 48
34 48 48
35 48 48