Bit Operators
C has several operators for logical bit-operations. For example,x = x & 0177;
forms the bit-wise AND of x
and 0177, effectively retaining only the last seven bits of x
. Other operators are| inclusive OR
^ (circumflex) exclusive OR
~ (tilde) 1's complement
! logical NOT
<< left shift (as in x<<2)
>> right shift (arithmetic on PDP-11; logical on H6070,
IBM360)
An unusual feature of C is that the normal binary operators like `+', `-', etc. can be combined with the assignment operator `=' to form new assignment operators. For example,x =- 10;
uses the assignment operator `=-' to decrement x
by 10, andx =& 0177
forms the AND of x
and 0177. This convention is a useful notational shortcut, particularly if x
is a complicated expression. The classic example is summing an array:for( sum=i=0; i<n; i++ )
sum =+ array[i];
But the spaces around the operator are critical! Forx = -10;
sets x to -10, whilex =- 10;
subtracts 10 from x. When no space is present,x=-10;
also decreases x by 10. This is quite contrary to the experience of most programmers. In particular, watch out for things likec=*s++;
y=&x[0];
both of which are almost certainly not what you wanted. Newer versions of various compilers are courteous enough to warn you about the ambiguity.Because all other operators in an expression are evaluated before the assignment operator, the order of evaluation should be watched carefully:
x = x<<y | z;
means ``shift x left y places, then OR with z, and store in x.'' Butx =<< y | z;
means ``shift x left by y|z places'', which is rather different.
0 comments:
Post a Comment