Binary operations in Java 5

Friday, June 24th, 2005...2:43 am

Jump to Comments

I’ve recently been doing some signal analysis work, which required a small bit of binary arithmetic, and I discovered several new binary-related methods that have been added to Java 5.

Many signal analysis algorithms require the input signal length to be a power of 2 (i.e., 2, 4, 8, 16, 64 … 1024…). What’s the most efficient method of checking if a number, i, is a power of 2? Well, you could think of a number of methods, e.g., for(i=0; 2^i<=n; i++) if 2^i == n then n is a power of 2, but that's just horrible. Far more efficient is to remember that numbers are stored in binary form:

1 = 00012 = 00104 = 01008 = 10009 = 1001

Now, it's fairly obvious that to determine if a given number (greater than 1) is a power of 2, is simply a matter of counting the on bits. Powers of 2, will have only 1 on bit. The old way to do this might be something like:

while(n > 0){  if((n & 1) == 1)    count++;  z = z >>> 1;}

In Java 5, there are some new binary-related methods in java.lang.Integer. Now, to count the number of one bits, just called Integer.bitCount(int n), e.g., Integer.bitCount(8) == 1, Integer.bitCount(9) == 2, etc.

My next task was to determine the number of padding zeros that would have to be added to a signal that was not a power of 2. If my signal length was 9, then I would like to pad this out to the next power-of-2, i.e., 16. Again, you could think of a complicated way of doing this, or just use a little binary trick and another new Java 5 method call:

9 = 100116 = 10000Integer.highestOneBit(9) = 8Integer.highestOneBit(9) << 1 = 16numPaddingZeros = (Integer.highestBit(9) << 1) - 9

Leave a Reply