Today, when I read the tree array, I suddenly found this thing and thought about it. Then I briefly proved it with text:
2^k = L and (L xor (L - 1) )
Set the first K-bit of I from the end of the binary value not to 0. first use C = I ^ (I-1), then the K to the left number to 0, from K to the right are 1 and then I & C because the end of C K is 1, K to left 0, I at the end of the k-1 is 0, K is 1, K to left do not know. After bitwise AND, the remaining number is 2 ^ (k-1)
The following is a program:
# Include <stdio. h> # include <math. h> # define num 16 // lowbit: Calculate 2 ^ K (2 ^ K = lowbit (I) when the number of zeros at the end of an integer in the binary is K) // set the first K-bit of I from the end of the binary value not to 0. // first use C = I ^ (I-1), then the K bit to the left of the number to 0, from K to the right are 1 // then I & C because K at the end of C is 1, K to left is 0, I at the end of the k-1 is 0, the K-bit is 1, and the K-bit is left unknown. // After bitwise AND, the remaining number is 2 ^ (k-1 ), // calculate 2 ^ K (2 ^ K = lowbit (I) when the number of 0 at the end of the integer in the binary is K) // to calculate the K value, you only need to perform the remainder operation at the base of 2. Int lowbit (int I) {return I & (I ^ (I-1);} int main (INT argc, char * argv []) {for (INT I = 1; I <num + 1; ++ I) {printf ("% d: \ t % d \ n", I, (INT) log2 (lowbit (I )));} return 0 ;}
After solving this problem, I suddenly thought of a problem. By following this method and modifying the program, I can find the bitwise inverted process in the FFT.
The Code is as follows: the bitwise reverse code in FFT can also be obtained by one digit or one digit, but it takes a lot of time when I is the k power of 2, at least one constant coefficient can be optimized:
#include <stdio.h>#include <math.h>#define NUM 16#define NUM_WEI 4 int lowBit(int i){ return i&(i^(i-1));} int ma_wei_dao_xu(int k){ int l; int sum = 0; while(k){ l = lowBit(k); sum += (int)pow(2,NUM_WEI - log2(l) - 1); k &= (NUM - l * 2); } return sum;} int main(int argc, char *argv[]){ for(int i = 0;i < NUM;++i){ printf("%d:\t%d\n",i,ma_wei_dao_xu(i)); } return 0;}
Follow-up:
When I was eating, I thought about the 4-digit saved time as C () + 2 * C () + 3 * C) + 4 * C (4, 4 );
The total time for n-bit binary numbers is: C (1, N) + 2 * C (2, n) + ..... + (N-1) * C (N-1, n) + N * C (n, n );
Because the total remaining time is the total number of 0. C (m, n) actually implies that the n-bit binary contains the number of M zeros, and the number of included Zeros is M * C (m, n );