Permission security and status-based ManagementProgramAnd found that numbers like Npower 2 are very useful. Because it is convenient for logical operations.
Sometimes it is necessary to verify whether a number is the n power of 2: I wrote a method today to find it very interesting. Of course, I am a cainiao, And the heroes saw it.
Static bool checknumifisnpoweroftwo (ulong num)
{
Console. writeline (datetime. Now. millisecond );
If (num = 0) return false;
Byte state = 0; // The value does not actually exceed 63
For (INT I = 0; I <64; I ++) // cyclically 64 times
{
If (Num-1 = (Num> = 1 ))
{State ++;
}
If (num = 1) break; // This loop determines whether the current bit is the same as the adjacent one on the left;
// When the frontend is the rightmost bit, the right shift operation actually fills in the symbol bit on the leftmost side (the unsigned value is 0, the signed value is 1, and here it is 0 ). Because 0 is supplemented, it is no longer the object we want to detect.
}
Console. writeline (datetime. Now. millisecond );
If (State = 1) return true;
Else return false;
}
It takes 3 ms to test uint. maxvalue.
Call
Ulong num = (ulong) uint. maxvalue + 1;
Console. writeline ("{0} is the Npower of 2? {1} ", num, checknumifisnpoweroftwo (Num ));