在C中生成随机32位十六进制值

sac*_*hin 1 c random hex

在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);
    }

}
Run Code Online (Sandbox Code Playgroud)

Mys*_*ial 10

x = rand() & 0xff;
x |= (rand() & 0xff) << 8;
x |= (rand() & 0xff) << 16;
x |= (rand() & 0xff) << 24;

return x;
Run Code Online (Sandbox Code Playgroud)

rand()不返回完整的随机32位整数.上次我检查它0和之间返回2^15.(我认为它依赖于实现.)所以你必须多次调用它并掩盖它.

  • 它返回0到RAND_MAX范围内的值 (4认同)