【发布时间】:2011-10-01 20:49:46
【问题描述】:
在 C 中生成随机 32 位十六进制值的最佳方法是什么?在我当前的实现中,我分别生成每个位,但输出不是完全随机的……许多值重复了几次。生成整个随机数而不是单独生成每个位更好吗?
随机数应该使用整个 32 位地址空间(0x00000000 到 0xffffffff)
file = fopen(tracefile,"wb"); // create file
for(numberofAddress = 0; numberofAddress<10000; numberofAddress++){ //create 10000 address
if(numberofAddress!=0)
fprintf(file,"\n"); //start a new line, but not on the first one
fprintf(file, "0 ");
int space;
for(space = 0; space<8; space++){ //remove any 0 from the left
hexa_address = rand() % 16;
if(hexa_address != 0){
fprintf(file,"%x", hexa_address);
space++;
break;
}
else if(hexa_address == 0 && space == 7){ //in condition of 00000000
fprintf(file,"%x", "0");
space++;
}
}
for(space; space<8; space++){ //continue generating the remaining address
hexa_address = rand() % 16;
fprintf(file,"%x", hexa_address);
}
}
【问题讨论】:
-
您当前的代码将与使用
rand生成单个 32 位值一样随机。随机数具有重复值。 -
为什么不直接调用随机数生成器呢?我忘记了 C 的 rand() 是否返回 64 位数量(或完全随机的 32 位),但还有其他的。而“十六进制”与 32 位数字有什么关系?
-
上面的评论假设 RAND_MAX 是最大 int