Bit wise Operators in C Language


Bit wise operators in C Language:

    • These operators are used to perform bit operations. Decimal values are converted into binary values which are the sequence of bits and bit wise operators work on these bits.
    • Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), << (left shift) and >> (right shift).
 Truth table for bit wise operation:                                          
Bit wise operators:
 x
y
 x|y
x & y
x ^ y
Operator_symbol
Operator_name
0
0
0
0
0
&
Bitwise_AND
0
1
1
0
1
|
Bitwise OR
1
0
1
0
1
~
Bitwise_NOT
1
1
1
1
0
^
XOR
<<
Left Shift
>>
Right Shift
  • Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y=  01010000
  • All bit wise operations for x and y are given below.
x&y = 00000000 (binary) = 0 (decimal)
x|y = 01111000 (binary) = 120 (decimal)
~x =1111111111111111111111111111111111111111111111111111111111010111
.. ..= -41 (decimal)
x^y = 01111000 (binary) = 120 (decimal)
x << 1 = 01010000 (binary) = 80 (decimal)
x >> 1 = 00010100 (binary) = 20 (decimal)
Note:
  • Bit wise NOT : Value of 40 in binary is 0000000000000000000000000000000000000000000000000000000000101000. So, all 0′s are converted into 1′s in bit wise NOT operation.
  • Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will be left shifted by one place. If we use it as “x << 2 “,  then, it means that the bits will be left shifted by 2 places.

Example program for bit wise operators in C language:

    • In this example program, bit wise operations are performed as shown above and output is displayed in decimal format.

Output:

AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20


 Continue on types of C operators:

S.no
Types of Operators
             Description              
1
Arithmetic_operatorsThese are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus
2
Assignment operatorsThese are used to assign the values for the variables in C programs.
3
Relational operatorsThese operators are used to compare the value of two variables.
4
Logical operatorsThese operators are used to perform logical operations on the given two variables.
5
Bit wise operatorsThese operators are used to perform bit operations on given two variables.
6
Conditional (ternary) operatorsConditional operators return one value if condition is true and returns another value is condition is false.
7
Increment/decrement operatorsThese operators are used to either increase or decrease the value of the variable by one.
8
Special operators&, *, sizeof( ) and ternary operators

www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

No comments: