I have an int m
and an unsigned int j
and want to determine whether they are both even or both odd.
In the past I've been using
if((int(j)+m)%2)
to catch the case that only one is odd. But I'm concerned about the casting to int
incorrectly changing the odd-even-ness of j
.
Do either of these run into problems?
if(!(j%2)!=!(m%2)) if(bool(j%2)!=bool(j%2))
I know that
if(j%2!=m%2)
doesn't work because 'm%2' will produce -1
when m
is negative, which will always evaluate to true
no matter what the value of j%2
is.
Signed numbers use sign flag or can be distinguish between negative values and positive values. Whereas unsigned numbers stored only positive numbers but not negative numbers.
Both can store 256 different values, but signed integers use half of their range for negative numbers, whereas unsigned integers can store positive numbers that are twice as large.
If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator % like this num % 2 == 0 . If a number divided by 2 leaves a remainder of 1, then the number is odd.
then your compiler may issue a warning like "comparison between signed and unsigned integer expressions". Briefly, the problem is that a standard C++ compiler will handle this code by casting x as an unsigned int before doing the comparison, which may turn a negative number into a large positive number.
Don't use %
. This is a problem that calls for bitmasks:
bool same_parity = (i & 0x1) == (j & 0x1);
This works regardless of the sign of i
, since the result of that expression will always be 0
or 1
.
if (1 & (i ^ j)) { // Getting here if i is even and j is odd // or if i is odd and j is even }
^
is the exclusive-or
bitwise operator, which checks each bit in both numbers if they have the same value. For example, if the binary representation of i
is 0101
and j
is 1100
, then i ^ j
will evaluate to 1001
, since their first and last bits are different, while the middle bits are the same.
&
is the and
bitwise operator, which checks each bit in both numbers if they are both 1
.
Since just the last bit of each number determines if it's even or odd, i ^ j
will evaluate to ...xxx0
if they are both even or odd, and ...xxx1
otherwise (the x
s don't matter, we aren't looking at them anyway). Since 1
is actually ...0001
, 1 & (i ^ j)
evaluates to 0
if i
and j
are both even or odd, and 1
otherwise.
This works on any combination of unsigned numbers, 2s-complement, and sign-and-magnitude, but not the rare 1s-complement if exactly one is negative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With