Shift Operators | |||
[Home] [Java] [HTML] [Tabs] [About Me] [Disclaimer] [All Downloads] [Contact] | |||
This page has moved to a new location, click here !
OK that said we can start with it . Why byte is not a byte anymore after a shift operation ? Lets assume the following block of code - When the above code is compiled you get
the following compile-time error - The reason for this is that the operands ( b & c ) are implicitly promoted to the int type before any binary operators are applied . Refer JLS 5.6.1 .
The same is true for short & char types as well . Before any binary operator is , applied arithmetic promotion of operands takes place so that the operands are at least of the type int . What is shifting anyways ? Shifting is basically taking the binary equivalent of a number & moving the bit pattern left or right . This is analogous to a queue - one bit moves forward & leaves while the one behind takes it's place . Simple ! This is exactly what the >> & << operators do ( >>> is a bit tricky ) . Try an example ! Consider 78 whose binary equivalent is Say you wanna shift it right ( >> ) 2 times , keeping that
queue in mind , here's what we get Similarly now lets shift left ( << ) 3 times & we get Now for some negative values - Shift left ( << ) 2 times & the result is Shift right ( >> ) 2 times & the result is Did I miss something up there !? When you shift left ( << ) the void left behind by the shift is filled by zero's but that's not the case when you shift right ( >> ) .
As for the bits in the extreme right ( rightmost bits ) , they're discarded . Try
right shifting ( >> ) these values - Note that right shifting ( >> ) always preserves the sign of the original number i.e. to say that a negative number will stay negative while a positive number will stay positive after a right shift ( >> ) . So what about the >>> ( unsigned right shift ) operator ? Sometimes we may require a right shift ( >> ) but we wouldn't like it to fill one's , instead we'd like it to fill zero's & only zero's no matter what . This is where the >>> ( unsigned right shift ) operator fits in . It fills the void left behind by the leftmost bits with zero's only .
So - That's all about there is to shifting . Practice with some code samples to get a hang of the concept . The applet you tried up there is available for download .If you'd like to download the applet do read the disclaimer first ! Read Disclaimer Download Applet . [Home] [Java] [HTML] [Tabs] [About Me] [Disclaimer] [All Downloads] [Contact]
|