 C++ Tutorials

# C++ Tutorials

Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of bits from right to left. Bitwise operators are not applied to float or double.

 Operator Description & Bitwise AND | Bitwise OR ^ Bitwise XOR << Left shift >> Right shift

Explanation :

& (Bitwise AND) – The Bitwise AND will take pair of bits from each position, and if only both the bit is 1, the result on that position will be 1. Bitwise AND is used to Turn-Off bits.

``````
int a = 10;
int b = 12;
int c = a & b;

``````

### Calculation :

```            bit
a =    1010
b =  & 1100
----------
c =    1000
----------
```
```    value of c = 8;
```

| (Bitwise OR) – The Bitwise OR, will take pair of bits from each position, and if any one of the bit is 1, the result on that position will be 1 else 0.

``````
int a = 10;
int b = 12;
int c = a | b;

``````

### Calculation :

```            bit
a =    1010
b =  | 1100
----------
c =    1110
----------
```
```    value of c = 14;
```

^ (Bitwise XOR) – The Bitwise XOR will take pair of bits from each position, and if both the bits are different, the result on that position will be 1. If both bits are same, then the result on that position is 0.

``````
int a = 10;
int b = 12;
int c = a ^ b;

``````

### Calculation :

```            bit
a =    1010
b =  ^ 1100
----------
c =    0110
----------
```
```    value of c = 6;
```

<< (Left shift) – Left shift operator will shift the bits towards left for the given number of times.

``````
int a = 6;
int b = a << 2;

``````

### Calculation :

```    a = 6
Position 7 6 5 4 3 2 1
6 in bit 0 0 0 0 1 1 0
Shifting 2 bit to left
Position 7 6 5 4 3 2 1
Result   0 0 1 1 0 0 0
```
```    value of b = 24;
```

>> (Right shift) – Right shift operator will shift the bits towards right for the given number of times.

``````
int a = 6;
int b = a >> 2;

``````

### Calculation :

```    a = 6
Position 7 6 5 4 3 2 1
6 in bit 0 0 0 0 1 1 0
Shifting 2 bit to right
Position 7 6 5 4 3 2 1
Result   0 0 0 0 0 0 1
```
```    value of b = 1;
```