Monday, May 7, 2012

Good tutorials on Bitwise operations in Java


Can anyone please point me to good online tutorials on Bitwise Operations (preferably in Java)? Before anyone write LMGTFY, I've already Googled it but couldn't find one with good examples. Java's own tutorial is also not that extensive and doesn't clearly explain what is going under the hood. I'm a visual learner; so, if there are any resources with good 'working' examples, that would help me a lot. Thanks.



Source: Tips4all

7 comments:

  1. Vipan Singla's page on Bitwise Operations is quite nice.

    It is not language specific, but luckily, these operations work the same on Java as many languages (in particular, nearly all C-style languages work this way with bitwise operations). It is very visual, and uses tables to illustrate what happens by operation.

    ReplyDelete
  2. Additionally to the good introductory guide that Reed Copsey recommended I'd recommend a intresting collection of small real world samples that show what you can actually do with bit operators and that you might enjoy reading and experimenting with once you have got some basic understanding of how bitwise operators work.

    Regarding the differences of bitwise operators between Java and C/C++: In Java you don't have unsigned numeric types (except char) but instead you have two right shift operators (>> and >>>) that allow you to do either a signed (>>) or a unsigned shift (>>>). A signed right shift copies the sign bit to all empty places on the left side while a unsigned right shift fills them with zero bits. Also, as booleans in Java cannot be be cast to ints, you cannot use boolean expressions directly as operands for bit operators. I.e. something like this works in C but not in Java:


    val |= ( a > b );


    In Java you would have to write this insead to do the same thing:


    val |= ( a > b ) ? 1 : 0;

    ReplyDelete
  3. What's wrong with the WIkipedia article?

    ReplyDelete
  4. A perennial favorite: Sean Eron Anderson's Bit Twiddling Hacks.

    ReplyDelete
  5. Aside from the >>> operator, Java's bitwise operators are very similar (identical?) to those in C. Thus, you could extend your search for decent tutorials/examples by looking in the C realm as well.

    A brief intro or reference: http://www.cprogramming.com/tutorial/bitwise_operators.html

    ReplyDelete
  6. As an introduction to bitwise operations to represent sets and efficiently compute subsets I liked this tutorial. It contains links to samples, including Java code (if you keep following the links at the bottom of the linked pages).

    ReplyDelete
  7. Also check Hacker's Delight, there is a sample chapter which is available online. Though not specific to Java, the programming tricks explained here would be applicable with Java also.

    ReplyDelete