简体   繁体   English

生成特定的32位二进制序列

[英]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'. 我需要生成这样的32位二进制序列:它具有八个'1',其余位为'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. 问题是要从32个中选择8个,因此有10518300个组合。 In other words, there are 10518300 sequences like my examples. 换句话说,有10518300个序列,例如我的示例。 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> . 最简单的编码解决方案是使用next_permutationvector<bool>

Prepare a vector with the earliest permutation in lexicographic order (ones are at the back). 准备一个按字典顺序排列最早的向量(后面是一个)。 Run next_permutation until it returns false . 运行next_permutation直到返回false Here is a demo code that generates all 8-bit sequences with three bits set: 这是一个演示代码,该代码生成设置了三位的所有8位序列:

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 . 这是运行演示程序的ideone链接

Your program will need a 32-bit vector with the last eight elements set to 1 . 您的程序将需要一个32位向量,最后八个元素设置为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. 无需打印序列中的元素,您需要将它们转换为32位int ,并将其存储在输出容器中。

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. 转到步骤2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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