Bitwise Pt. 2
Left shift (<<) Operator
-
First operand << Second operand
-
First operand : whose bits get shifted
-
Second operand : Decides the number of places to shift the bits
Important Points
- When bits are shifted left then trailing positions are filled with zeros.
int main() {
// char = 1 byte = 8 bits
char var = 3; // Note : 3 in binary = 0000 0011
printf("%d", var << 1); // Result : 0000 0110 = 6
return 0;
}
- Left shifting is equivalent to multiplication by 2 power of rightOperand
Example:
var = 3
var << 1 Output: 6 [3 x 2ยน]
var << 4 Output: 48 [3 x 2โด]
Right shift (>>) Operator
-
First operand >> Second operand
-
First operand : whose bits get shifted
-
Second operand : Decides the number of places to shift the bits
Important Points
- When bits are shifted right then leading positions are filled with zeros.
int main() {
char var = 3; // Note : 3 in binary = 0000 0011
printf("%d", var >> 1); // Result : 0000 0001 = 1
return 0;
}
- Right shifting is equivalent to division by 2 power of rightOperand
Example:
var = 3;
var >> 1 Output: 1 [3 / 2ยน] (decimal points are eliminated)
var = 32;
var >> 4 Output: 2 [32 / 2โด]