4 ms·
In two's complement, -2 means all bit are 1, except for the lowest. 1 is all bits are zero, except for the lowest. So it's basically the same, just negated. If
by roetlich 3y ago
In two's complement, -2 means all bit are 1, except for the lowest.
1 is all bits are zero, except for the lowest. So it's basically the same, just negated.
If you look at the generated code, this is used to the opposite: Keep all bits, except the least significant.
Btw, it's a lot simpler if you use only unsigned ints. Both GCC and clang add a couple more instructions to make it work with negative numbers. With unsigned ints, both gcc and clang generate this simple assembly code:
is_even:
mov eax, edi
and eax, 1
ret
- Joker_vD 3y agoAnd those additional instructions are there only because C modulo is defined to have the same sign as the dividend (so that e.g. -5 % 2 == -1 instead of 1). Had it been defined as being always positive, &1 would have been sufficient in all cases (that would also have the effect of making integer division round to negative infinity instead of zero which too can be implemented simply by >>1, for both signed and unsigned numbers).
- teo_zero 3y agoThank you, today I've learned something new. So the easiest answer to the original question (whether a number is even or odd) likely involves &1, not %2. Note taken.