#include<iostream.h>
#include<conio.h>
main()
{
clrscr();
int a,b,c,d,e;
a=25;
b=15;
c=a&b; // &-->And Operator
d=a|b; // |--> Or Operator
e=~a; // ~a Negation of a
cout<<" a&b="<< c;
cout<<"\n a|b="<< d;
cout<<"\n ~a="<< e;
getch();
}
------------------------------------------------
Define Bitwise Operator
The bitwise operators operate on numbers (always integers) as if they were sequences of binary bits (which, of course, internally to the computer they are). These operators will make the most sense, therefore, if we consider integers as represented in binary, octal, or hexadecimal (bases 2, 8, or 16), not decimal (base 10). Remember, you can use octal constants in C by prefixing them with an extra 0 (zero), and you can use hexadecimal constants by prefixing them with 0x (or 0X).
The & operator performs a bitwise AND on two integers. Each bit in the result is 1 only if both corresponding bits in the two input operands are 1. For example, 0x56 & 0x32 is 0x12, because (in binary):
0 1 0 1 0 1 1 0
& 0 0 1 1 0 0 1 0
---------------
0 0 0 1 0 0 1 0
The | (vertical bar) operator performs a bitwise OR on two integers. Each bit in the result is 1 if either of the corresponding bits in the two input operands is 1. For example, 0x56 | 0x32 is 0x76, because:
0 1 0 1 0 1 1 0
| 0 0 1 1 0 0 1 0
---------------
0 1 1 1 0 1 1 0
The ^ (caret) operator performs a bitwise exclusive-OR on two integers. Each bit in the result is 1 if one, but not both, of the corresponding bits in the two input operands is 1. For example, 0x56 ^ 0x32 is 0x64:
0 1 0 1 0 1 1 0
^ 0 0 1 1 0 0 1 0
---------------
0 1 1 0 0 1 0 0
The ~ (tilde) operator performs a bitwise complement on its single integer operand. (The ~ operator is therefore a unary operator, like ! and the unary -, &, and * operators.) Complementing a number means to change all the 0 bits to 1 and all the 1s to 0s. For example, assuming 16-bit integers, ~0x56 is 0xffa9:
~ 0 0 0 0 0 0 0 0 0 1 0 1 0 1 1 0
-------------------------------
1 1 1 1 1 1 1 1 1 0 1 0 1 0 0 1
The << operator shifts its first operand left by a number of bits given by its second operand, filling in new 0 bits at the right. Similarly, the >> operator shifts its first operand right. If the first operand is unsigned, >> fills in 0 bits from the left, but if the first operand is signed, >> might fill in 1 bits if the high-order bit was already 1. (Uncertainty like this is one reason why it's usually a good idea to use all unsigned operands when working with the bitwise operators.) For example, 0x56 << 2 is 0x158:
0 1 0 1 0 1 1 0 << 2
-------------------
0 1 0 1 0 1 1 0 0 0
And 0x56 >> 1 is 0x2b: 0 1 0 1 0 1 1 0 >> 1
---------------
0 1 0 1 0 1 1
For both of the shift operators, bits that scroll ``off the end'' are discarded; they don't wrap around.
No comments:
Post a Comment