Bit Tricks

Java 1.5 defines new bit-manipulation methods on Integer and Long. These are one of the minor changes attributable to Josh Bloch. Here's some code to play around with them.

static void bitTricks(int x) {
    // Approximate log2() with numberOfLeadingZeros()
    if (x > 0) 
	System.out.printf("base-2 log of %d is between %d and %d%n", x,
			  Integer.SIZE-1-Integer.numberOfLeadingZeros(x),
			  Integer.SIZE-Integer.numberOfLeadingZeros(x-1));

    // If 1 bits in an int are used to represent members of a set, then
    // bitCount() and highestOneBit() allow efficient counting and
    // iteration of the members of the set
    System.out.printf("%d has %d bits set.%n", x, Integer.bitCount(x));
    System.out.print(x + " = ");
    while(x != 0) {
	int highbit = Integer.highestOneBit(x);  // Get the highest bit
	System.out.print(highbit + "+");         // Print it out
	x &= ~highbit;                           // Clear it
    }
    System.out.println("0");
}

Books

ECMAScript 5 & HTML5!

"A must-have reference"
Brendan Eich,
creator of JavaScript

JavaScript graphics makes web programming fun again!

Read Less, Learn More

Comprehensive coverage of Ruby 1.8 and 1.9

"The New Most Important Ruby Book"
Peter Cooper,
rubyinside.com

The classic Java quick-reference

About

Advertising

Pages

Hosted By

Powered by Movable Type 4.21-en