Reliable Software Logo

C++ In Action: Language

Exercises

Compare with solutions.


In C++ one can perform bitwise operations on integral numbers. Binary bitwise operators AND and OR are denoted by ampersand & and vertical bar | respectively. The usage is

int i = 3;  // binary 0011
int j = 5;  // binary 0101
int k = i & j; // binary 0001
k = i | j;  // binary 0111
k = k | 8;  // binary 1111

Bitwise complement is denoted by a tilde ~. For instance (on a four-bit computer), if k = 13 (binary 1101) than its complement j = ~k would be equal to 2 (binary 0010) (ones become zeros and zeros become ones).

Binary Bitwise Operators
& bitwise and
| bitwise (inclusive) or
^ bitwise exclusive or (xor)
>> right shift by n bits
<< left shift by n bits
Unary Bitwise Operator
~ one's complement

  1. Add bitwise operations to our calculator.
  2. Add a new command, 'x', that toggles between decimal and hexadecimal outputs.

    To output a number in the hexadecimal (base sixteen) one sends a modifier "hex" to the output.

    using std::hex;
    int i = 11;
    cout << hex << i;   // i will be printed in hex as 'b'.
  3. Create a "logical calculator" that operates on Boolean values. Instead of numbers, it accepts t and f for true and false. It performs logical and, or, and not, and accepts &, |, and ! as tokens (notice the not is a unary operation--it takes one argument). Send the manipulator std::boolalpha to the output stream before printing Boolean values.
  4. Extend the calculator by adding symbolic variables denoted by lowercase letters. Add the assignment operation that assigns a value to a symbolic variable. For instance, one should be able to do the following
    > a
    > 5
    > =     // a = 5
    > 2
    > a
    > *    // 2 * 5

    Consider what should the Calculator do with a symbol. For instance, what should it push on the stack?

NextNext: Pointers