88 Introduction to C++ Programming and Graphics
For example, the following code contained in the filebinary.ccwritten by
Fred Swartz prints the binary number of a specified integer,n, described by 32
bits:
for (int i=31; i>=0; i--)
{
intm=n>>i;
int bit = m & 1;
cout << bit;
}
The idea is to successively shift to the right the binary digits ofn, and then
sample the last digit using the bitwiseandoperation with the number 1 whose
binary representation is:
00 ... 0001
In other applications, theoroperator is used to ensure that a given bit
of a given integer is set to 1, while thexoroperator is used to toggle two bits.
Problems
3.9.1.Describe the combined action of the following statements:
x = x^y; y = x^y; x = x^y;
3.9.2.Write a code that uses bitwise operations to assess whether a given in-
teger is a power of two.
Hint: The binary string of the even integer 2pconsists of zeros led by
one, whereas the binary string of the odd integer 2pā1 consists of ones.
3.9.3.Write a code that deduces whether the fifth binary digit of an integer is
1or0.
3.10 Preprocessor define and undefine
The C++ preprocessor assists the compilation process by making substitutions
and by inserting and removing chunks of code. It is important to realize that
the preprocessor does not interpret C++ code, and only performs mechanical
tasks reminiscent of cut-and-paste.
Consider the following code involving thedefinepreprocessor directive:
#include <iostream>
using namespace std;