Question
Now here is a puzzle to ponder: Using just the integer operators and , determine a set of three assignment statements that exchanges the values
Now here is a puzzle to ponder: Using just the integer operators and
, determine a set of three assignment statements that exchanges the values stored in two integer variables without using a third temporary variable.
Using the exclusive-or operator to exchange the values of two variables without an extra temp variable is a neat trick, but using a temporary variable is the more common and direct way to accomplish the task.
Are the bitwise operators useful for anything practical? Indeed they are. The power to change a single bit in an integer from 0 to 1 or vice versa, does come in handy. For example, a word processing program may offer you the following five independent formatting features:
With a single mouse click, you can turn each of these features on or off. Of course, a word processing application must keep track of which features are on and which are off. This bookkeeping can be done quite simply by manipulating the bits of a single integer.
Use the five rightmost bits of an integer (or a single byte) to store information about which options (a through e) are turned on. For example:
000 11111 indicates all five properties are turned on; the five rightmost bits are 1.
000 00101 indicates that boldface (a) and underlining (c) are turned on.
000 01000 indicates that subscripting is turned on; fourth bit from the right is 1.
To implement this scheme, declare five final variables:
and another variable to hold the information about which features are on or off.
int format 0 ; // stored as 00000000 indicates that initially all features are off
You can use the exclusive-or operator to change any particular bit of the variable format from 0 to 1 or from 1 to 0 . For example, to store the fact that the boldface and italics features are active, use the statements:
format format ^ BOLDFACE // 00000000 ^ 00000001 00000001
format format ^ ITALICS // 00000001 ^ 00000010 00000011
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started