Bitwise Shift Operators
The Bitwise Shift Operators, as the name suggests, operate on the bit pattern by shifting it. But here is a great observation, I will explain it but first I am going to intro the BITWISE SIFT in this matter. You can skip about these bitwise shift operator if you know about these very will and look at the 🌟 point.
Two way to sift bitwise,
Bitwise left shift (<<):
The Left Shift Operator, as you can guess, shifts the bit pattern to the left. As the bits are shifted to the left, the right-most bit positions are filled with zeros. As the bits are shifted to the left, all the left-most bits shifted beyond the MSB position, are discarded.
For example:
1010 1101 << 1 = 0101 1010
1010 1101 << 2 = 1011 0100
Bitwise right shift (>>):
The Right-Shift operator has the same properties and characteristics as the Left-Shift operator, however, the bits are shifted to the Right instead.
Bits are shifted to the right, the left-most bit positions are filled with zeros and all the right-most bits shifted beyond the LSB position, are discarded.
For example:
1010 1101 >> 1 = 0101 0110
1010 1101 >> 2 = 0010 1011
🌟 Now, the observation. When we shift left one time the actual decimal value turned to its double. I mean,
Let's say, the binary of 4 is 0100, now shift it left by 1.
0100 << 1 = 1000 (8)
See that, after shifting 1 time, it goes double (4 to 8).
4 << 1 = 4 * 2
4 << 3 = 4 * (2 * 2 * 2) [2^3]
And right shift means, as it is but divided by 2^n.
5 >> 1 = 5 / 2 = 2 (not 2.50 as the integer value)
5 >> 3 = 5 / (2 * 2 * 2)
So We can use 3 << 4 instead of 3 * 16
Comments
Post a Comment