Tuesday, July 14, 2009

What do the operators |=, ~ and >> do in C?

This better not be for a take-home exam!!!





The |= operator is actually two operators, | and =. First a bitwise OR of the left-hand argument and the right-hand argument is performed. Next, the result of the bitwise OR operation is assigned to the variable on the left-hand side. Another name for this operator is "bitwise inclusive or and assign". An example:


char a, b, c;


a = 'a'; // a == 0x61, or 01100001


b = 'b'; // b == 0x62, or 01100010


c = b;


c |= a; // after this operation, c == 01100011 (0x62, or 'c' in ASCII)





The ~ operator, in C, does a bitwise complement, or negation, of its argument. For example, if the argument is 00100100, the result of the operation will be 11011011.





The %26gt;%26gt; operator, in C, is a bitwise-shift operator, specifically bitwise shift right. The result of this operation is the left-hand arguments' bits shifted to the right the number of times specified by the right-hand value. For example:


int n = 4;


int m = n %26gt;%26gt; 2;


// After the assignment, m == 00000001 (truncating to one byte)


This has the effect of dividing by 2 the number specified by the right-hand argument times.





In C++, the ~ and %26gt;%26gt; operators gain additional meanings.

What do the operators |=, ~ and %26gt;%26gt; do in C?
The operator != is NOT-EQUAL. It is the opposite of == (EQUAL). The ~ operator (tilde) is the BINARY-NOT operator. It inverts all of the bits in a number. For example if you do ~0x00FFFF00 you'll get 0xFF0000FF. The %26gt;%26gt; operator is known as the EXTRACT operator in C++, and also known as the RIGHT-SHIFT operator in C. It shifts the number in binary to the right the number of places thats on the right of the operator, this effectively divides by 2.





For example: 32 %26gt;%26gt; 1 = 16. 32 %26gt;%26gt; 2 = 8. 2 %26gt;%26gt; 1 = 1. It is almost the opposite of doing %26lt;%26lt; (LEFT-SHIFT operator)
Reply:the first is a binary operator meaning





a |= b





or





a = a | b;





the second is used for destructors, dont use it other than that cuz its just to signify an inverse function. for example





constructor MyClass(){}


Destructor ~MyClass(){}





or bit inversion, again binary. means not 1 or not 0. but this is usually denoted by ! again meaning not or inverse. for example





true and not false = true


true %26amp;%26amp; !false = true.





and the last is a shift. can do powers quick. you should never use these, make code readable adn clear. the compiler will use these if it sees fit, its much better at programming than you.





and the last is the bunary shif operator
Reply:hahah, good answer
Reply:Use the textbook. We answer people ain't in the business of doing your take-home final for you.

buy flowers

No comments:

Post a Comment