If you have the binary number 10110 how can I get it to return 11111? e.g a new binary number that sets all bits to 1 after the first 1, there are some likewise examples listed below:
101 should return 111 (3 bit length)
011 should return 11 (2 bit length)
11100 should be return 11111 (5 bit length)
101010101 should return 111111111 (9 bit length)
How can this be obtained the easiest way in Java? I could come up with some methods but they are not very “pretty”.
You could use this code:
The idea is that leftmost 1 will get copied to all positions on the right.
EDIT: Also works fine with a negative
value. If you replaceintwithlong, add one extra|=statement:value |= (value >> 32). In general, last shift must be a power of 2 that is at least half ofvaluesize in bits.