282 Chapter 12 Operations on Bits
When using constants in performing bitwise operations, it is usually more convenient
to express the constants in either octal or hexadecimal notation.The choice as to which
to use is usually influenced by the size of the data with which you are dealing. For
example, when dealing with 32-bit computers, hexadecimal notation is often used
because 32 is an even multiple of 4 (the number of bits in a hexadecimal digit).
Program 12.1 is presented to illustrate the bitwise AND operator. Because you are
dealing with only positive values in this program, all integers have been declared as
unsigned intvariables.
Program 12.1 The Bitwise AND Operator
// Program to demonstrate the bitwise AND operator
#include <stdio.h>
int main (void)
{
unsigned int word1 = 077u, word2 = 0150u, word3 = 0210u;
printf ("%o ", word1 & word2);
printf ("%o ", word1 & word1);
printf ("%o ", word1 & word2 & word3);
printf ("%o\n", word1 & 1);
return 0;
}
Program 12.1 Output
50 77 10 1
Recall that if an integer constant has a leading 0, it represents an octal (base 8) constant
in C.Therefore, the three unsigned ints,word1,word2,and word3,are given initial octal
values of 077 , 0150 ,and 0210 ,respectively. Recall also from Chapter 4 that if a uor U
follows an integer constant, it is treated as unsigned.
The first printfcall displays octal 50 as the result of bitwise ANDing word1with
word2.The following depicts how this value was calculated:
word1 ... 000 111 111 077
word2 ... 001 101 000 & 0150
------------------------------
... 000 101 000 050
Only the rightmost nine bits of the previous values are shown because all bits to the left
are 0 .The binary numbers have been arranged in groups of three bits to make it easier
to translate back and forth between binary and octal.