Abhinav Sau
Abhinav Sau

Reputation: 31

Bitwise modulus computation

Given two numbers a and b where b is of form 2k where k is unknown.What would be the efficient way of computing a%b using bitwise operator.

Upvotes: 2

Views: 605

Answers (1)

Louis Ricci
Louis Ricci

Reputation: 21116

a AND (b-1) == a%b (when b is 2^k)

ex. a = 11 (1011b), b = 4 (0100b)
11 / 4 = 2 R3
11 % 4 == 11 AND (4-1)
11 (1011b) AND 3 (0011b) == 3 (0011b)

Upvotes: 3

Related Questions