Is there a fast way to find if a 32-bit integer is a multiple of 4 without using the % operator (In C++)?
1 Answer
yes, there is.
((i & 3) == 0)
Note that this may not be any faster. Also a good optimizing compiler will convert your modulus against constant 4 to the fastest operation anyway, so it may well generate this automatically.
Check the generated code if you are interested.
-
And it's not actually guaranteed to work by the C++ standard, although only for the rather unlikely reason that C++ implementations are permitted to use 1s' complement representation of negative integers. Commented Jul 11, 2012 at 16:14
-
I tested on GCC 4.6.3 and identical code was produced. The compiler is smart enough to know that a constant modulus that's a power of two is identical to a bitwise AND with a number one less than the modulus on that platform. (Interestingly,
andl
on x86_64 andtestb
on x86_32. Go figure.) Commented Jul 11, 2012 at 20:42
%
operator? When you have a tool that's specifically designed for precisely the task at hand, you have to wonder when someone specifically insists you not use it.return (c%4) == 0;
andreturn (c & 3) ==0;
produce identical code. The compiler knows they're equivalent. Both became two assembly instructions,andl
thensete
.