One, calculates the number of 1 in the binary representation of a positive
1 //solving 1 of digits in binary notation for positive numbers2 Private Static intCountbit (intnum) {3 intCount = 0;4 for(; num > 0; count++)5 {6Num &= (num-1);7 }8 returncount;9}
Algorithm idea: Every for loop, the rightmost 1 of NUM's binary is cleared.
Why is n &= (n–1) able to erase the rightmost 1? Because from the binary point of view, N is equivalent to the lowest bit of n-1 plus 1. For example, 8 (1000) = 7 (0111) + 1 (0001), so 8 & 7 = (+) & (0111) = 0 (0000), the 8 rightmost 1 is cleared (actually the highest 1, because there is only one 8 in the binary of 1). For example, 7 (0111) = 6 (0110) + 1 (0001), so 7 & 6 = (0111) & (0110) = 6 (0110), the rightmost 7 of the binary representation of 1 (that is, the lowest bit 1) is cleared.
Reference: algorithm-Finding the number of 1 in a binary number
Two, get the first bit of a number (to determine if the first bit of a number is 0 or 1?). )Train of thought: if the first and 1 phase and the result of 1 indicate that the first bit is 1; If 0 indicates that the I bit is 0
// gets the value of the first bit of the integer num Private Static boolean getbit (intint i) { return (Num & (1 << i)! = 0); // True indicates that the first bit is 1, otherwise 0 }
1 left I bit, get a number, this number is only the first I bit 1, the other bits are 0
Num with this number, the result is either 0, or not 0. The result is a non-0 indicating that the I bit is 1, and the result is 0 that the I bit is 0
Third, set the I bit to 1Idea: The first bit with 0 or, the value does not change. The first bit with 1 or, becomes 1. Therefore, our goal is num with an i-bit value of 1, the value of the other bits is 0 of the number of phases or
// Place The value of the I bit of the integer num at 1 Private Static int getbit (intint i) { return (num | (1 << i)); }
Four, set the I bit to 0 (clear 0)Idea: The first and 0 and the first I bit will become 0. The other bits are the same as the 1 and the other bits remain unchanged. In this way, I'm only going to clear the first 0.
// Place The value of the I bit of the integer num at 1 Private Static int getbit (intint i) { int mask = ~ (1 << i);//000100
return (num & mask);//111011 }
In short, to get the value of the I-bit, or I position 0 or 1, the overall idea is: Move 1 left I bit, and then proceed with operation or OR operation.
Common bits operations in Java