Java – understanding integer Logic behind the implementation of highestonebit() method
The Java integer class has a static method, highestonebit method, which will return a value with a single bit, which is located in the highest bit of the specified value. If the specified value itself is equal to zero, it will return zero
For example, the input of int 17 will return 16; Because 17 can be expressed in binary as 10001, it will return the farthest bit left, equal to 16
In the integer class, it has the following implementation in Java doc
public static int highestOneBit(int i) { // HD,figure 3-1 i |= (i >> 1); i |= (i >> 2); i |= (i >> 4); i |= (i >> 8); i |= (i >> 16); return i - (i >>> 1); }
I just want to know the logic behind implementing it in this way and using the shift operation Anyone can know something about it
Solution
The algorithm calculates a given I, whose binary representation is:
0..01XXXXXXX...XXXX
value
0..011111111...1111
This is what the 5 | = operator does
Then, in the return statement, it subtracts the value shifted one bit to the right
0..001111111...1111
Get results
0..010000000...0000
How it works:
The highest possible bit is the 32nd (leftmost) bit Assume that the input number is 1 in this bit:
1XXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX
You or the value of this value shifts right by 1 (I > > 1) and gets
11XXXXXX XXXXXXXX XXXXXXXX XXXXXXXX
Then you or the value of the new value shifts right by 2 (I > > 2) and get
1111XXXX XXXXXXXX XXXXXXXX XXXXXXXX
Then you or the value of the new value shifts to the right by 4 (I > > 4) and get
11111111 XXXXXXXX XXXXXXXX XXXXXXXX
Then you or the new value of that value shifts right by 8 (I > > 8) and gets
11111111 11111111 XXXXXXXX XXXXXXXX
Finally, you or the new value of the value shifts to the right 16 (I > > 16) and gets
11111111 11111111 11111111 11111111
If the highest bit is less than the 32nd bit, these operations still change all bits to the right of it to 1 and keep the rest (higher bits) to 0