Java "Bit Shifting" Tutorial? [closed]
Well, the official Java tutorial Bitwise and Bit Shift Operators covers the actual operations that are available in Java, and how to invoke them.
If you're wondering "what can I do with bit-shifting", then that's not Java specific, and since it's a low-level technique I'm not aware of any list of "cool things you can" do per se. It'd be worth becoming familiar with the definitions, and keeping your eyes open for other code where this is used, to see what they've done.
Note that often bit-twiddling is an efficiency gain at the expense of clarity. For example, a << 1
is usually the same as a * 2
but arguably less clear. Repeated XORs can swap two numbers without using a temporary variable, but it's generally considered better form to write the code more clearly with the temporary variable (or even better, in a utility method). So in this respect it's hard to give great examples, because you're not likely to achieve anything new or profound on an architecture level; it's all about the low-level details. (And I'd estimate that a vast number of uses of bit-twiddling "in the wild" are instances of premature optimisation.)
When using the shift operator, be very careful not to repeat a common error!!
As the following SO post suggests, the author of the accepted answer mentions:
"In some languages, applying the shift operators to any datatype smaller than int automatically resizes the operand to be an int."
This is absolutely crucial to remember when operating on bytes for example, otherwise you may get unexpected results (as I did).
Given a byte with the following bit pattern:
1001 0000
When I tried to bit shift by 4, and assigned to an int, such as:
int value = byteValue >>> 4;
I would expect to have:
0000 1001 (or a value of 9)
But I would get a HUGE number! That's because the byteValue is casted to int BEFORE the bit shift operation, thus resulting in something like this instead:
1111 1111 1111 1111 1111 1111 1001