The Problem description often encounters a problem in programming, that is, in a 32-bit integer, the first bit is 1 from right to left. Such a problem is very common, and in the face of such a problem, a common solution is to traverse all the bits in this integer one by one until a bit is encountered. If the first bit with a value of 1 appears in the high area, the bit-by-bit comparison method is not time.
In another way, when we look for a certain number in an array, what can we do? It is feasible to traverse the entire array in simple order. The time complexity is O (n ). What if the array is an ordered array? We usually search for a number in an array by two points, which is faster, and the time complexity is O (logn ). In a 32-bit int, can I use the 2-point lookup method to find the first number with 1?
When we look for the first BIT with 1, we can use the 2-point lookup method. How can we use the 2-point method? Do not forget bitwise operations for bit-related operations. The effective use of bitwise operations is a two-point search method for this problem.
How does one perform a 2-point search?
When determining whether a single digit is 1, you can use & Operations. How can we determine if 16 digits in 32 bits have 1? Use Data & 0xffff. If you want to determine whether 8 bits have 1, you can use data & 0xff to determine whether 4 bits have 1 and can use data & 0xf to determine whether 2 bits have 1, you can use data & 0x3.
After analysis, you can use data and 0 xFFFF, 0xff, 0xf, and 0x3 operations.
Implementation Code
int binarysearch1(int data){int pos=0;if ((data & 0xFFFF) == 0){data >>= 16; pos += 16;}if ((data & 0xFF) == 0){data >>= 8;pos += 8;}if ((data & 0xF) == 0){data >>= 4; pos += 4;}if ((data & 0x3) == 0){data >>= 2; pos += 2;}if ((data & 0x1) == 0)pos += 1;return pos;}
Summary bit operations are very important in the C language. Many skillful optimizations are achieved through bit operations and must be mastered.