next up previous
Next: About this document ... Up: quiz1-ans Previous: Problem 2: Some Utter:

Problem 3: Basically Annoying-Just Answer

In the spririt of Lab 1, solve the following bit puzzles. Don't be upset if you don't finish them.

  1. Write a C code fragment similar to those in Lab 1, satisfying the following specification.

    /* 
     * 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 $T_{min} $, since it is the same as its complement, it gives the wrong result.

  2. Suppose that variables v, w, and mask have been declared as ints in C on a machine with 16 bit integers. What bit pattern should mask be set to so that w is the absolute value of v. Your answer should be in either base 2 or base 16. Show your work to be eligible for partial credit.

    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.

  3. Briefly explain the result of the C code fragment below. That is, what is the output value of the function? Be as specific as possible.

    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.


next up previous
Next: About this document ... Up: quiz1-ans Previous: Problem 2: Some Utter:
MM Hugue 2008-10-01