C Bitwise Operators

Bitwise operators interpret operands as strings of bits. Bit operations are performed on this data to get the bit strings. These bit strings are then interpreted according to data type. There are six bit operators: bitwise AND(&), bitwise OR(|), bitwise XOR(^), bitwise complement(~), left shift(<<), and right shift(>>). We use bitwise operators in some programming contexts because bitwise operations are faster than (+) and (-) operations and significantly faster than (*) and (/) operations. Here is a program which demonstrate C bitwise operator:
01.#include <stdio.h>
02./* a demonstration of C bitwise operators */
03.void main()
04.{
05.int d1 = 4,/* 101 */
06.d2 = 6,/* 110*/
07.d3;
08. 
09.printf("\nd1=%d",d1);
10.printf("\nd2=%d",d2);
11. 
12.d3 = d1 & d2; /* 0101 & 0110 = 0100 (=4) */
13.printf("\n Bitwise AND  d1 & d2 = %d",d3);
14. 
15.d3 = d1 | d2;/* 0101 | 0110 = 0110 (=6) */
16.printf("\n Bitwise OR d1 | d2 = %d",d3);
17. 
18.d3 = d1 ^ d2;/* 0101 & 0110 = 0010 (=2) */
19.printf("\n Bitwise XOR d1 ^ d2 = %d",d3);
20. 
21.d3 = ~d1; /* ones complement of 0000 0101 is 1111 1010 (-5) */
22.printf("\n Ones complement of d1 = %d",d3);
23. 
24.d3 = d1<<2;/* 0000 0101 left shift by 2 bits is 0001 0000 */
25.printf("\n Left shift by 2 bits d1 << 2 = %d",d3);
26. 
27.d3 = d1>>2;/* 0000 0101 right shift by 2 bits is 0000 0001 */
28.printf("\n Right shift by 2 bits d1 >> 2 = %d",d3);
29.}
And here is the output
d1=4
d2=6
Bitwise AND d1 & d2 = 4
Bitwise OR d1 | d2 = 6
Bitwise XOR d1 ^ d2 = 2
Ones complement of d1 = -5
Left shift by 2 bits d1 << 2 = 16
Right shift by 2 bits d1 >> 2 = 1

source:cprogramlanguage.net

No comments:

Post a Comment