algorithm - What is a good way to iterate a number through all the possible values of a mask? -


Looking at a bitmask where the set bits are described where the second number can be one or zero and without set bits that number Should be zero in What is a good way to recycle through all possible values? For example:

  000 returns [000] returns 001 [000, 001] 010 returns [000, 010] 011 returns [000, 001, 010, 011] 100 Returns [000, 100] 101 Returns [000, 001, 100, 101] 110 Returns [000, 010, 100, 110] 111 Returns [000, 001, 010, 011, 100, 101, 110, 111] < / Code>  

The easiest way to do this would be to:

  zero f (int m) {int i; {If (i == i & amp; m) printf ("% d \ n", i) for (I = 0; i & lt; = m; i ++); }}   

But it runs again through several numbers. This 32 should not be in the 2nd ** 32 order.

A bit-twitching trick (This description is detailed in detail that Knuth "Computer Programming Art of "Vol. 4A.7.1.3; see p. 150):

A mask mask and the current combination bits , you

  bits = (bits - mask) can make the next combination; Start the mask   

... 0 and keep running until you return to 0. (Use an unsigned integer type for portability; it is a non-two-in-execution machine with a signed integer. An unsigned integer is a better option for a value which is considered as a set of beats.)

In the example C:

  #include & lt; Stdio h & gt; Static zero testing (unsigned intersection) {unsigned int bits = 0; Printf ("test% u:", mask); Do {printf ("% u", bits); Bit = (bits - mask) & amp; Mask; } While (bits = 0); Printf ("\ n"); } Int main (zero) {unsigned int n; For (n = 0; n & lt; 8; n ++) test (n); Return 0; }   

returns:

  test 0: 0 test 1: 0 test 2: 0 2 test 3: 0 1 2 3 test 4: 0 4 test 5: 0 1 4 5 test 6: 0 2 4 6 test 7: 0 1 2 3 4 5 6 7   

(... and I agree that 000 must be [000] !)

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

python - referencing a variable in another function? -