This post is completed by 2 users
|
Add to List |
298. Left Shift (<<) and Right Shift (>>) Operators
What is Left Shift (<<) Operator:
- a<<b means left shift the bits of number a by b places.
- 3<<2 means left shift the bits of number 3 by 2 places. Result = 12
- 011 is the bit representation of number 3.
- Left shift all the bits so => 0 1 1 0 (number =6)
- Left shift all the bits so => 0 1 1 0 0 (number = 12).
- Each time you left shift the number, it will be multiplied by 2. So if you shift by a number by k then number will be multiplied by k2.
What is Right Shift (>>) Operator:
- a>>b means right shift the bits of number a by b places.
- 12>>2 means right shift the bits of number 12 by 2 places. Result = 3
- 0 1 1 0 0 is the bit representation of number 12.
- Right shift all the bits so => 0 1 1 0 (number =6)
- Right shift all the bits so => 0 1 1 (number = 3).
- Each time you right shift the number, it will be divided by 2. So if you shift by a number by k then number will be divided by k2. (Keeps only integer).
Output:
n<<1, Left shift by 1 of n: 10 is : 20 n>>1, Right shift by 1 of n: 10 is : 5 n<<1, Left shift by 1 of n: 62 is : 124 n>>1, Right shift by 1 of n: 62 is : 31