Java "Bit Shifting" Tutorial?

Markus picture Markus · Jun 6, 2011 · Viewed 86.5k times · Source

I would be thankful for a good tutorial, that explain for java newbies how in java all the "bit shifting" work.

I always stumble across it, but never understood how it works. It should explain all the operations and concepts that are possible with byteshifting/bitmanipulation in java.

This is just an example what I mean, (but I am looking for a tutorial that explains every possible operation):

byte b = (byte)(l >> (8 - i << 3));

Answer

Andrzej Doyle picture Andrzej Doyle · Jun 6, 2011

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.)