How it is possible to check if one integer number stored in a variable is even or odd, looking at its last digit? (I've already seen many answers determining it by the reminder doing a modulo operation, but, I mean, since a binary-number's last digit can be 0 xor 1, and assumed that it is 0, the number is even, else the number is odd, wouldn't it be much faster to simply look at its last digit?)
CodePudding user response:
Assuming two's complement (or unsigned) numbers, which are guaranteed by C 20, and were nearly ubiquitous before:
bool even = !(x & 1);
CodePudding user response:
Use
bool even = !(x % 2);
to test evenness for any integral type x. You could use flashy XOR tricks but then you are doing the compiler's job, not your job. The compiler will make the appropriate optimisation. Yes XOR is normally an extremely fast machine-level instruction, to the point you see REG XOR REG to set REG to 0 when looking at generated assembly, rather than a write to 0.
The correct way using XOR is to write
bool even = (x & 1) ^ ((-1 & 1) | ((x < 0) ? 0 : 1));
assuming x is a signed type. Any other way and you are assuming something about the complementing scheme of x. You can't assume 2's complement until C 20.
CodePudding user response:
wouldn't it be much faster to simply look at its last digit?
Checking last bit will be faster not slower than calculating x % 2 and comparing that to 0.
However, your compiler will most certainly do that optimization. So write your code in a manner that is easy to understand and maintain.
