简体   繁体   中英

generating specific 32-bit binary sequence

I need to generate such a 32-bit binary sequence: it has eight '1' and the rest bits is '0'. So written in hex, some of the sequences will be like these:

000000FF
000001FE
000001FD
000001FB
000001F7
...

The problem is to choose 8 from 32, so there are 10518300 combinations. In other words, there are 10518300 sequences like my examples. I will appreciate it if you give me any suggestions or algorithm to generate my desired sequences.

This problem is about making permutations of zeros and ones. The easiest to code solution is to use next_permutation and a vector<bool> .

Prepare a vector with the earliest permutation in lexicographic order (ones are at the back). Run next_permutation until it returns false . Here is a demo code that generates all 8-bit sequences with three bits set:

vector<bool> data(8, false);
data[7] = data[6] = data[5] = true;
do {
    for (int i = 0 ; i != data.size() ; i++) {
        cout << (int)data[i];
    }
    cout << endl;
} while (next_permutation(data.begin(), data.end()));

Here is a link to ideone with a running demo .

Your program will need a 32-bit vector with the last eight elements set to 1 . Instead of printing the elements of the sequence, you would need to convert them to a 32-bit int , and store them in the output container.

Design:

  1. Define an ordering for the combinations such that one comes first, one comes last, and each one has a place in that sequence.

  2. Write an algorithm to convert a sequence to the next sequence according to the ordering you made.

  3. Implement that algorithm in code.

Implementation:

  1. Set the sequence to the first sequence according to your ordering.

  2. Output the current sequence.

  3. If this is the last sequence stop.

  4. Go to the next sequence using the algorithm you implemented.

  5. Go to step 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM