Please explain about the Right and Left shift operators in java.. I am new to programming concepts.. So please explain me with examples..
Basically it shifts bits.
Take for example, the number 4. In binary, its 0100. Each digit in the binary for is called bits. 8 bits = 1 byte.
If we use the bitshift operator like this
int shiftVal = 1; int value = (4 << shiftVal);
we shift the bits to the right, shiftVal amount of times. Since shiftVal
is 1, we shift all the bits 1 position to the right, so :
4 = 0100
//after shifting 1 bit
val = 1000;
lets take another example, consider the number 1. It binary for is
0001. If we do this , (1 << 4). That means we shift all the bits
in the number 1, 4 times to the left. So
//before the shift
1 = 0001
val = 10000
notice the 1 moved to the right 4 times. The left shift operator( >> )
works similar except it shift all bits to the left x amount of times.