[英]Generate an array of numbers from a number and a mask of bits in C++
I would like to create a function that returns an array (or vector) of numbers from a bit mask, my function header would be: 我想创建一个从位掩码返回数字数组(或向量)的函数,我的函数头为:
vector generateArray(int number, int maskSize)
if I call this function this way: 如果我这样调用此函数:
generateArray(4,2)
4 being equal to 100 in binary, 4等于二进制100
it would return a vector with these numbers: 5 , 6 , 7 which are in binary 101,110 and 111. So the function changed all the 2 last bits of the number 100 to generate all the possibilities. 它将返回一个具有以下数字的向量:5,6,7,它们位于二进制101,110和111中。因此该函数更改了数字100的所有最后2位以生成所有可能性。
I have no clue how to do it .. any idea would help a lot ! 我不知道该怎么做..任何想法都会有很大帮助!
Thanks in advance 提前致谢
Your mask size can be thought of as a way to generate all numbers that can be represented using maskSize
bits. 掩码大小可以认为是生成可以使用
maskSize
位表示的所有数字的一种方式。 In your example that is 2
or 2 bits, which has 2 2 possible values: 00 01 10 11, or 0, 1, 2, 3, which if you add each of those to number
gives you 4, 5, 6, and 7. 在您的示例中,该位是
2
或2位,它具有2 2个可能的值:00 01 10 11或0、1、2、3,如果将每个number
加到number
得到4、5、6和7 。
So what you do is compute all the numbers that can be reached from 2 maskSize and add those to `number' to fill out your array. 因此,您要做的就是计算从2 maskSize可以到达的所有数字,并将这些数字添加到“数字”中以填写您的数组。
This should do the trick - 这应该可以解决问题-
void generateArray(int n, int m) {
if (m == 0) {
printf ("%d\n", n);
return;
}
int mask = 1 << (m-1);
generateArray(n & ~mask, m-1);
generateArray(n | mask, m-1);
}
This c code prints out the numbers, but the principle is the same - just modify it to accumulate them in your vector, and remove the initial parameter. 此C代码可以打印出数字,但原理是相同的-只需对其进行修改以将其累加到向量中,然后删除初始参数即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.