Programming and Graphics

(Kiana) #1

3.9 Bitwise operators 85


The C++ compiler interprets the “greater than” or “less than” comparison in
the expected alphabetical sense.


Problems


3.8.1.Modify the bubble-sort code to arrange the array in descending order
with the smallest number put at the bottom.


3.8.2.Discuss whether it is possible to insert a stopping check in the selection-
sort algorithm.


3.8.3.Alphabetize a list of ten cities.


3.9 Bitwise operators...........................


In the binary system, an integer,a, is expressed as the modulated sum of powers
of two,


a=bk× 2 k+bk− 1 × 2 k−^1 +...+b 1 × 21 +b 0 × 20 , (1)

wherebi=0,1 are the binary digits (bits). The binary representation of this
integer is


a=(bkbk− 1 ...b 1 b 0 ) 2.

For example,


50 = 1× 25 +1× 24 +0× 23 +0× 22 +1× 21 +0× 20 , (2)

and thus,


50 = (110010) 2. (3)

Ifais declared as a short integer, the binary digits are stored in a two-byte
memory block consisting of sixteen memory cells, as:


00 ... 0 bkbk− 1 ...b 1 b 0 (4)

where an appropriate number of leading bits on the left are set to zero. Thus,
the number 50 is stored as:


0000000000110010 (5)

The bitwise operators of C++ allow us to produce new integers by
manipulating the bits of a given integer.

Free download pdf