# Thread: Shift Off Trailing Zeroes

1. Member
Join Date
Oct 2008
Posts
45
Rep Power
0

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

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

3. How about:

Java Code:
```int i = 24;
i >>= Integer.lowestOneBit(i)/2 - 1;
System.out.println(i);```

4. Member
Join Date
Oct 2008
Posts
45
Rep Power
0
That's interesting. However, when I try Integer.lowestOneBit(108), it's giving me 4 rather than 3.

5. Member
Join Date
Oct 2008
Posts
45
Rep Power
0
Ah. Integer.numberOfTrailingZeros seems to do the trick. Thanks!

6. Originally Posted by nwboy74
Ah. Integer.numberOfTrailingZeros seems to do the trick. Thanks!
Have you seen the code? Here it is:

Java 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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•