/*
* isEqual - return 1 if x == y, and 0 otherwise
* Examples: isEqual(5,5) = 1, isEqual(4,5) = 0
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 6
* Rating: 2
*/
int isEqual(int x, int y) {
return !(x^y);
}
Why does that work? Because (x==y)
if and only if (x^y) is a string of zeros, and 1==!0.
Any equivalent expression should have received full credit.
And for those of you who answered !!(~x^y)
and assumee the number and its complment would give all ones
whenever x==y, forgot about
, since it is
the same as its complement, it gives the wrong result.
w = (v ^ mask) - mask
Answer: The short answer is that mask is textttv
(15).
And, by the way, typically the term mask implies a
constant. However, this problem did not rule out masks depending on
the
input parameters; so, you should have received full credit for
anything that gave a correct result.
I'll be releasing a more detailed answer for this later.
int mystery(int x) {
int result = (x & 0xff) << 24;
result |= ((x >> 8) & 0xff) << 16;
result |= ((x >> 16) & 0xff) << 8;
result |= ((x >> 24) & 0xff);
return result;
}
Answer: This will swap the bytes in x. That is, if we label the bytes (ABCD), where A is the MSB(most significant byte) and D is the LSB (least significant byte), then the result of mystery(ABCD) is DCBA. Note that the bit order is not affected. To see this, let each small letter represent a 4-bit quantity. If you follow the code carefully, you will find that (ab)(cd)(ef)(gh) is converted to (gh)(ef)(cd)(ab) by mystery().
Oh, and a few of you got a note from me because you did a beautiful job working through this problem to an answer. That's the kind of answer that will get you full credit on exams.