Given a 32 bit int, it is known for at least 2 bits set, but besides all it is clearly scanned Is there a way to do 2 most important set bits? That is, I want to ensure that there are exactly 2 beet sets in the output.
What if the input is only guaranteed of 2 or 3 bit sets.?
Example:
0x2040 -> 0x2040 0x0300 - & gt; 0x0300 0x010 9 - & gt; 0x0108 0x5040 - & gt; 0x5000 Benchmarking results:
Code:
query performance frequency (& amp; Freq); / *********** / value = (base = 2). 1; QueryPerformanceCounter (& amp; Beginning); For (l = 0; l Core2Duo E7500 @ 2.93 GHz results on using VS 2005 default release settings:
--------- Baseline 1000000 loops 0.001630 seconds taken --------- Sirgidas 1000000 loops 0.002479 seconds (0.000849 additional) Word / sec = 1178.074206 million --------- ashelly 1000000 loops 0.004640 seconds (0.003010 additional) Words / Sec = 332.23036 9 million --------- MVDS 1000000 loops 0.005250 seconds (0.003620 additional) word / sec = 276.242030 million --------- Spenders 1000000 loops 0.009594 seconds (0.007964 additional) sh If / sec = 125.566361 million --------- schnaader 1000000 loops 0.025680 seconds (0.024050 additional) words / second = 41.580158 million If the guarantee of input is certain that there are 2 or 3 bits then the answer can be counted very quickly, we take advantage of the fact that x x (x -1) X is cleared by LSB. Applying that expression twice to the input will generate 0, if 2 or fewer bits will be set. If exactly 2 bits are set, then we return the original input. Otherwise, we return the original input with LSB.
The code here is C ++:
assumes that one actually has 2 or 3 bits int int two bits (int a) {int b = A & amp; (A-1); // B = A with LSB approved Return B & B (B-1)? B. A; // Check that on clearing B's LSB, it can be written as a deceptive single expression, if you prefer: Int topTwoBitsOf (Int a) {one (& amp; a-1) & amp; ((A and (A-1)) - 1)? One more (A-1): A; }
Comments
Post a Comment