Alright, so I have seen << and >> in a few different Java Programs and I have an idea of what they do, but I have no idea what you would use them for. I haven't ran into a problem where I need to use them, so if someone could explain exactly what they do and give and show some examples of when and why you would need them, that would be much appreciated.

3 Years
Discussion Span
Last Post by Doogledude123

In java, x<<y shifts x y bits to the left. x>>y arithmetically shifts x y bits to the right. x>>>y logically shifts x y bits to the right.

These operations are invaluable when you need to manipulate individual bits of a value.

For example, lets say you are using a bitmask to store 10 booleans in one integer. You can use | (or) to 'set' a bit, & (and) to 'clear' a bit, and ^ (xor) to swap a bit. However, to actually use these operations you would want to have access to the bits. You could do this manually: x|0x10 to set bits 2 and 4. However, bitshift operators let you do this generically: x|(1<<2)|(1<<4) also sets bits 2 and 4. As you can tell, the second version lends itself very nicely to being put into a method, while the first version does not.

There are many more uses of the shift operators in some advanced algorithms, since many of them use the fact that any number has a binary representation to decompose the number into its components (by stripping 1's and bitshifting right). For example you can fairly quickly calculate the remainder of a number by using the method of squaring.


Seems highly complicated, and in my opinion not needed, at least for my applications. Thanks for the answer though!


Here's a less esoteric example that is used all the time in image processing...
a common way to store a pixel is an a 32 bit int, with the red, green and blue values each occupying one byte of the int. Here's how you extract those values:

int r = (pixel >> 16) & 0xff;
int g = (pixel >> 8) & 0xff;
int b = (pixel) & 0xff;

Creating an int with new rgb values is the reverse of that, also using shifts to put each byte in the right pkace.


Definitely a better, more practical example! Thanks James!
Something I might come across eventually :P

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.