Programming in C

(Barry) #1
Bit Operators 283

The second printfcall results in the display of octal 77 ,which is the result of
ANDing word1with itself. By definition, any quantity x,when ANDed with itself, pro-
duces x.
The third printfcall displays the result of ANDing word1,word2,and word3togeth-
er.The operation of bitwise ANDing is such that it makes no difference whether an
expression such as a & b & cis evaluated as (a & b) & cor as a & (b & c),but for
the record, evaluation proceeds from left to right. It is left as an exercise to you to verify
that the displayed result of octal 10 is the correct result of ANDing word1with word2
with word3.
The final printfcall has the effect of extracting the rightmost bit of word1.This is
actually another way of testing if an integer is even or odd because that rightmost bit of
any odd integer is 1 and of any even integer is 0 .Therefore when the ifstatement


if ( word1 & 1 )


is executed, the expression is true if word1is odd (because the result of the AND opera-
tion is 1 ) and false if it is even (because the result of the AND operation is 0 ). (Note:On
machines that use a ones complement representation for numbers, this does not work for
negative integers.)


The Bitwise Inclusive-OR Operator


When two values are bitwise Inclusive-ORed in C, the binary representation of the two
values are once again compared bit by bit.This time, each bit that is a 1 in the first value
ora 1 in the second value produces a 1 in the corresponding bit of the result.The truth
table for the Inclusive-OR operator is shown next.


b1 b2 b1 | b2


0 0 0
0 1 1
1 0 1
1 1 1


So, if w1is an unsigned intequal to octal 0431 and w2is an unsigned intequal to
octal 0152 , then a bitwise Inclusive-OR of w1and w2produces a result of octal 0573 as
shown:


w1 ... 100 011 001 0431
w2 ... 001 101 010 | 0152


... 101 111 011 0573


As was pointed out with the bitwise AND operator, be sure to not confuse the opera-
tion of bitwise ORing (|) with that of logical ORing (||), the latter operation being
used to determine if either of two logical values is true.

Free download pdf