|
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
|
- Add bitwise operations to our calculator.
- 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'.
|
- 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.
- 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?
|