Bitwise Manipulation:
Bit
manipulation is the act of algorithmically manipulating bits or other pieces
of data shorter than a byte. C language is very efficient in manipulating
bits.
Here
are following operators to perform bit manipulation:
Bitwise Operators:
Bitwise
operator works on bits and perform bit by bit operation.
Assume
if B = 60; and B = 13; Now in binary format they will be as follows:
A =
0011 1100
B =
0000 1101
-----------------
A&B
= 0000 1100
A|B =
0011 1101
A^B =
0011 0001
~A
= 1100 0011
Bitwise
operators supported by C language with Description and Example
The shift operators perform appropriate shift by operator on the
right to the operator on the left. The right operator must be positive. The
vacated bits are filled with zero.
For
example: x << 2 shifts the bits in x by 2 places to the left.
Uses of Bitwise Operators
Therefore
a shift left is equivalent to a multiplication by 2. Similarly a shift right
is equal to division by 2. Shifting is much faster than actual multiplication
(*) or division (/) by 2. So if you want fast multiplications or division by
2 use shifts.
|
Bitwise AND is often used to test whether a particular bit is 1 or
0.
Bitwise OR is often used to set a particular bit to 1.
Bitwise COMPLIMENT is often combined with AND to turn off a particular bit.
We can also use bits to represent elements of a (small) set. If a
bit is 1, then element i is in the set, otherwise it's not.
We can use bitwise AND to implement set intersection, bitwise OR
to implement set union.
No comments:
Post a Comment