Chapter2 Review#1 (With Answers)


  1. On a 32 bit machine, if the int x >= 0, what is x >> 31?

    Answer: 0 = 0x00000000

    What is x >> 31 if x < 0?

    Answer: -1 = 0xFFFFFFFF

  2. What is the hex representation of the int value -33?

    Answer: 0xFFFFFFDE

    x = 33 = 0x00000033. So -x = ~x + 1 = 0xFFFFFFDE

  3. Convert between decimal, binary, and hex representation of (non-negative) integers.

    (See practice problem 2.3)

    Decimal Binary Hexadecimal
    35 0010 0011  0x23 
    74  0100 1010  0x4A
    104  0110 1000 0x68 
  4. Using only bit operations and logical operations, write an expression in integers x and y which is 1 if x == y and 0 otherwise.

    Operations allowed: & | ~ ! && ||

    Answer: !(x ^ y)

  5. C rules mandate that logical right shift is used for u >> n if the type of u is unsigned.

    If x is an integer of type signed (char, short, int), C rules allow a compiler to use either logical right shift or arithmetic right shift for >> n.

    However, C compilers generally all use arithmetic right shift for signed integers.

    For byte integers and assuming C uses arithmetic right shift for signed integers fill in the table below using hex notation for these values of signed byte integer x (type char) and unsigned byte integer u(type: unsigned char):

    char x = 0xC8
    unsigned char u = 0xC8
    Operation Value
    x << 1 0x90 
    u << 1 0x90 
    x >> 4 0xFC 
    u >> 4 0x0C 
    x >> 1 0xE4 
    u >> 1 0x64 
  6. (See practice problem 2.14) Fill in the following table in hex notation if x = 0x3C and y = 0x57

    Expression Value Expression Value
    x & y 0x14  x && y 1 
    x | y 0x7F  x || y 1 
    ~x | ~y 0xEB  !x || !y 0 
    x & !y 0x00  x && ~y 1 
  7. Write a C expression in terms of the int variable x that yields a value equal to:

    1. the least significant byte is unchanged and all other bits are set to 1.
      Example: x = 0x00badfad, result = 0xffffffad

      Answer: x | ~0xFF

    2. the least significant byte is complemented and all other bits are set to 1.
      Example: x = 0x00badfad, result = 0xffffff52

      Answer: ~x | ~0xFF

    3. the least significant byte is complemented and all other bits are left unchanged.
      Example x = 0x00badfad, result = 0x00badf52,

      Answer(s):
      (1) (x & ~0xFF) | (~x & 0xFF), or
      (2) x ^ 0xFF, or
      (3) (x & (0xFF << 24)) | (x & (0xFF << 16)) | (x & (0xFF << 8)) | (~x & 0xFF)