Bitwise Operator
Bitwise Operator
These operators can operate on ints and chars but not floats and
doubles.
• the bit numbering scheme in integers and
characters. Bits are numbered from zero onwards,
increasing from right to left as shown below:
showbits( )
• to display the binary representation of any integer or character
value.
One’s Complement Operator
• all 1’s present in the number are changed to 0’s and all 0’s are changed to
1’s.
• One’s complement operator is represented by the symbol ~.
where could the one’s complement
operator be useful?
• in the development of a file encryption utility
Right Shift Operator &Left Shift Operator
• The right shift operator is represented by >>.
• It needs two operands.
• It shifts each bit in its left operand to the right. The number of places
the bits are shifted depends on the number following the operator
(i.e. its right operand).
if the variable ch contains the bit pattern 11010111,
then, ch >> 1 would give 01101011 and
ch >> 2 would give 00110101.
• In the explanation a >> b if b is negative the result is unpredictable.
• If a is negative, then its leftmost bit (sign bit) would be 1.
• On some computer right shifting a would result in extending the sign bit.
For example, if a contains -1, its binary representation would be 1111111111111111.
• the bits are shifted to the left, and for each bit shifted, a 0 is added to the right of
the number.
Get a year as a separate entity from the two bytes
entry
Finally, for obtaining the day, left shift date by 11 and then right shift the result
by 11. Left shifting by 11 gives 0100100000000000.
Right shifting by 11 gives 0000000000001001.
Bitwise AND Operator
• operator is represented as &.
• The & operator operates on two operands.
• While operating upon these two operands they are compared on a
bit-by-bit basis. Hence both the operands must be of the same type
(either char or int).
• The second operand is often called an AND mask.
• The best use of the AND operator is to check whether a particular bit of an
operand is ON or OFF.
• used to turn OFF a particular bit in a number.
Given bit pattern 10101101 of an operand, How do
you check whether bit number 3 is ON (1) or OFF
(0)?
Bitwise OR and Bitwise XOR Operator
• ORing is represented as |. 1st bit 2nd bit 1st bit | 2nd bit
• ORing of two bits: 0 0 0
0 1 1
1 0 1
1 1 1
• The OR operator returns 1 when anyone 1st bit 2nd bit 1st bit ^ 2nd bit
of the two bits or both the bits are 1, whereas 0 0 0
XOR returns 1 only if one of the two bits is 1. 0 1 1
1 0 1
• XOR operator is used to toggle a bit ON or OFF. 1 1 0
A number XORed with another number twice
gives the original number. The truth table for the XOR operator