C – Bitwise Operators 2017-08-05T17:55:37+00:00

# Bitwise Operators :

Bitwise operators operate on individual bits of integer (int and long) values. This is useful for writing low-level hardware or OS code where the ordinary abstractions of numbers, characters, pointers, and so on, are insufficient. Bit manipulation code tends to be less “portable”. Code is “portable” if without any programmer intervention it compiles and runs correctly on different types of computers. The bit wise operations are commonly used with unsigned types.  These operators perform bit wise logical operations on values. Both operands must be of the same type and width: the resultant value will also be this type and width.

Biwise operators are:

~   Bitwise Negation one’s complement (unary)
&   Bitwise And
|    Bitwise Or
^   Bitwise Exclusive Or
>> Right Shift by right hand side (RHS) (divide by power of 2)
<< Left Shift by RHS (multiply by power of 2)

Definition of bitwise logical operators:

 Bit a Bit b a & b a | b a ^ b ~a 0 0 0 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 0

Example:

Bitwise Negation
a=00000011
~a =11111100

Bitwise And
a    =  00000011
b    =  00010110
a&b=00000010

Bitwise Or
a   = 00000011
b   = 00010110
a|b=00010111

Bitwise Exclusive Or
a  =   00000011
b  =   00010110
a^b=00010101

Right Shift
a = 0000 0011 = 3
(a<<=1) = 00000110 = 6
(a<<=2) = 00011000 = 24
(a<<=3) = 11000000 = 192

Left Shift
a=11000000     =192
(a>>=1) = 01100000 = 96
(a>>=2) = 00011000 = 24
(a>>=3) = 0000 0011 = 3

C – BITWISE OPERATOR EXAMPLE PROGRAM :

Output:

 a = 2    b = 22 a = 3 , ~a = -4 a & b = 2 a | b = 23 a ^ b = 21 a = 3 a << = 1 =6 a <<= 2 =24 a<<=3 =192 a = 192 a>>=1  = 96 a>>=2 = 24 a>>=3 = 3