Java – delete the lowest bit
•
Java
Given a binary number, what is the fastest way to delete the lowest bit?
01001001010 – > 01001001000
It will be used in the code to iterate over the bits of the variable The pseudo code is as follows
while(bits != 0){ index = getIndexOfLowestOrderBit(bits); doSomething(index); removeLowestOrderBit(bits); }
The possible languages I'm considering are C and Java
Solution
Well... In your example, you already know the bit index Then it's easy to:
bits &= ~(1 << index);
This masks the bits whose index is an index, regardless of their position in the value (highest, lowest, or middle) Think about it, of course you can use the fact that you know the bit has been set and clear it again with XOR:
bits ^= (1 << index);
This saves inversion, which may be a machine command
If you want to mask the lowest setting bit without knowing its index, the trick is:
bits &= (bits - 1);
For example, see here
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码