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

时间:2011-10-01 20:49:46

标签: 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);
    }

}

3 个答案:

答案 0 :(得分:10)

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

return x;

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

答案 1 :(得分:0)

这样做,它创建的数字比以前的逻辑大。如果您对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);
}

答案 2 :(得分:-1)

您可以创建任意随机数,该数字至少为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是一个包含八个随机十六进制数字的字符串。不要忘记为各种伪随机数生成器播种(分别使用srand48()srand()作为#1和#2)。由于您基本上必须使用至少一个32位整数从随机源播种PRNG,您也可以直接点击随机源(除非您使用time()或“非随机”之类的这一点)。