# Shift Off Trailing Zeroes

• 02-24-2010, 07:05 PM
nwboy74
Shift Off Trailing Zeroes
Is there an easy/fast way to shift off trailing zeroes from a binary number? Suppose I have the number 108 (1101100). I'd like to turn that into 27 (11011) as quickly and efficiently as possible. I could run it through a loop until mod 2 is 1, but I wasn't sure if there was some nifty bitwise operation that could be applied to get the same result more efficiently.
• 02-24-2010, 09:44 PM
JosAH
Quote:

Originally Posted by nwboy74
Is there an easy/fast way to shift off trailing zeroes from a binary number? Suppose I have the number 108 (1101100). I'd like to turn that into 27 (11011) as quickly and efficiently as possible. I could run it through a loop until mod 2 is 1, but I wasn't sure if there was some nifty bitwise operation that could be applied to get the same result more efficiently.

The 'best' (mind the quotes) I can come up with is an ugly mixture of Integer.lowestOneBit( ... ) and a switch with 32 case statements ...it is conceptually fast though ...

kind regards,

Jos
• 02-24-2010, 10:28 PM
mrmatt1111

Code:

```int i = 24; i >>= Integer.lowestOneBit(i)/2 - 1; System.out.println(i);```
• 02-24-2010, 10:47 PM
nwboy74
That's interesting. However, when I try Integer.lowestOneBit(108), it's giving me 4 rather than 3.
• 02-24-2010, 10:57 PM
nwboy74
Ah. Integer.numberOfTrailingZeros seems to do the trick. Thanks!
• 02-25-2010, 08:56 AM
JosAH
Quote:

Originally Posted by nwboy74
Ah. Integer.numberOfTrailingZeros seems to do the trick. Thanks!

Have you seen the code? Here it is:

Code:

```    public static int numberOfTrailingZeros(int i) {         // HD, Figure 5-14         int y;         if (i == 0) return 32;         int n = 31;         y = i <<16; if (y != 0) { n = n -16; i = y; }         y = i << 8; if (y != 0) { n = n - 8; i = y; }         y = i << 4; if (y != 0) { n = n - 4; i = y; }         y = i << 2; if (y != 0) { n = n - 2; i = y; }         return n - ((i << 1) >>> 31);     }```
My crude suggestion of using lowestOneBit() followed by an ugly switch of 32 cases is faster imho.

kind regards,

Jos