如何随机挑选基于所述位的位置的值 [英] How to randomly pick a value based on the position of the bit

查看:144
本文介绍了如何随机挑选基于所述位的位置的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以选择基于位位置的值。这个问题的说法是: -
对于16位的位置上,我可以设置任何位,说我设定1,4,6,7,11,13位
所以掩模将是: -

Is there a way to pick a value based on the bit position. The problem statement is:- for a 16 bits position, I can set any bits, say I set 1,4,6,7,11,13 bit so the mask would be:-

Bit Positons 0 0 1 0 1 0 0 0 1 1 0 1 0 0 1 0

现在我需要随机挑选基于此位掩码,其中只有1位设置的值,所以我可能的值可以是: -

Now I need to randomly pick a value based on this bit mask, where only 1 bit is set, so my possible values could be:-

有关选择4:0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0

For selecting 4 :0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0

用于选择7:0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0

但我需要随机选择这个值,所以我虽然做这样的

But I need to select this value randomly, so I though of doing it like this

1)创建一个基于位掩码的数组,因此16位,数组将有16个独特的价值。

1)Create an Array based on the bit mask, so for 16 bit , the array would have 16 unique values.

2)现在做兰特操作上的排列位置,以获得数组索引。

2) Now do the rand operation on the array position to get the array index.

3)在该数组索引使用的值。

3) Use the value at that array index.

是否有这样做的更好的办法?

Is there a better way of doing it?

推荐答案

如果我理解正确的话,你想与一个位组也是在掩码中设置了许多。

If I understand correctly you want a number with exactly one bit set that is also set in the mask.

要做到这一点,我会做一个while循环,直到它找到一个也是在面罩设置选择0至16之间的随机值:

To do this I'd make a while loop that selects a random value between 0 and 16 until it has found one that is also set in the mask:

uint16_t mask = 0x28d2; /* == 0 0 1 0 1 0 0 0 1 1 0 1 0 0 1 0 */
int bit = 0;

do{
    bit = 1 << (rand() % 16); /* sets one random bit between 1 and 16 */
}while(!(mask & bit)); 

/* bit has now exactly one bit set that is also set in mask */

这篇关于如何随机挑选基于所述位的位置的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆