我需要生成一个掩码向量(无符号字符类型),它只包含“1”中的2,即0x03、0x50等。
我还需要这两个‘1’在向量中随机分布。
我怎么能用c/c++?
谢谢您!
编辑:
这里提出一个更具挑战性和普遍性的案例。
How to generate n random 1s in an unsigned char array in c/c++?
最佳答案
我想这样做:
srand(time(0));
int s[8];
for (int i=0; i<8; i++) s[i] = i;
// s[0], s[1] are two random locations for '1's
u = rand()%8;
swap(s[0], s[u]);
v = rand()%7+1;
swap(s[1], s[v]);
unsigned char c = (1 << s[0]) | (1 << s[1]);
关于c++ - 如何在c/c++中生成两个随机1合一的无符号字符?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7748666/