在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);
}
}
x = rand() & 0xff;
x |= (rand() & 0xff) << 8;
x |= (rand() & 0xff) << 16;
x |= (rand() & 0xff) << 24;
return x;
rand()
不返回完整的随机32位整数。上次我检查它在0
和2^15
之间返回。 (我认为这取决于实现。)因此,您必须多次调用它并屏蔽它。
用这种方法。它创建的数字比以前的逻辑大。如果您对MSB感兴趣,则下面的逻辑很好。:
/** x = rand() ^ rand()<<1; **/
#include <algorithm>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
#include <string>
#include <stdio.h>
int main () {
int i, n;
n = 50;
uint x,y ;
//4294967295 :UNIT_MAX
/* Intializes random number generator */
srand((unsigned) time(0));
for( i = 0 ; i < n ; i++ ) {
/**WAY 1 **/
x = rand() ^ rand()<<1;
printf("x:%u\t",x);
printf("Difference1:(4294967295 - %u) = %u\n",x,(4294967295 - x));
/**WAY 2 **/
y = rand() & 0xff;
y |= (rand() & 0xff) << 8;
y |= (rand() & 0xff) << 16;
y |= (rand() & 0xff) << 24;
printf("y:%u\t",y);
printf("Difference2:(4294967295 - %u) = %u\n",y,(4294967295 - y));
printf("Difference between two is = %u\n",(x) - (y));
}
printf("End\n");
return(0);
}
您可以创建any至少32位宽的随机数,并将其格式化为十六进制。示例:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
uint32_t n;
n = mrand48(); // #1
n = rand(); // #2
FILE * f = fopen("/dev/urandom", "rb");
fread(&n, sizeof(uint32_t), 1, f); // #3
// ... etc. etc. E.g. Windows Crypto API
char hex[9];
sprintf(hex, "%08X", n);
现在hex
是一个包含八个随机十六进制数字的字符串。不要忘了为各种伪随机数生成器添加种子(分别为#1和#2使用srand48()
和srand()
)。由于本质上您必须使用至少一个32位整数从随机源中植入PRNG,因此您也可以直接点击随机源(除非您使用的是time()
或类似的“非随机”对象) 。