please explain left shift and right shift operator in detail , with multiple examples,
Left shift and right shift operator
<< (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift. Or in other words left shifting an integer “x” with an integer “y” (x<<y) is equivalent to multiplying x with 2^y (2 raise to power y).
>> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.Similarly right shifting (x>>y) is equivalent to dividing x with 2^y.
Above is the formal example but let me explain you by some examples
eg :- take example of 5
binary equivalent of 5 is 00101
so by performing left shift , you are shifting the bits to right and placing 0 at the rightmost position 5<<1 (1 which is the second operand represents the number of bits you have to shift) will be 001010 and right shift will shift the bits right by the specified position eg
5<<1 will be equivalent to 00010 notice the number of bits doesn’t change the previous rightmost bit is replaced by the bit on its left same for every bit
eg :
7>>2 = (000111)>>2 =(000001) = 1
7<<3 = (000111)<<3 = (111000) = 56
you will notice that each time you are shifting bits to the right , you are actually dividing the number by 2 and in case of right shift you are multiplying the number by 2.
this property is used widely in programming practice as binary operations are faster than arithmetic operations like * / so will widely see example like
int mid = (start+end)>>1;
Best way to understanding this is by practicing
In case of any doubt feel free to ask