C Random Number Generation (pure C code, no libraries or functions)

后端 未结 7 1426
时光取名叫无心
时光取名叫无心 2021-01-21 03:11

I need to generate some random numbers in C for testing and debugging the system. The system is a custom hardware (SoC) with a limited set of functions so I can only use basic m

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-21 03:45

    You can try Multiply-with-carry by George Marsaglia.

    Code from Wikipedia:

    #include 
    
    #define PHI 0x9e3779b9
    
    static uint32_t Q[4096], c = 362436;
    
    void init_rand(uint32_t x)
    {
        int i;
    
        Q[0] = x;
        Q[1] = x + PHI;
        Q[2] = x + PHI + PHI;
    
        for (i = 3; i < 4096; i++)
                Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i;
    }
    
    uint32_t rand_cmwc(void)
    {
        uint64_t t, a = 18782LL;
        static uint32_t i = 4095;
        uint32_t x, r = 0xfffffffe;
        i = (i + 1) & 4095;
        t = a * Q[i] + c;
        c = (t >> 32);
        x = t + c;
        if (x < c) {
                x++;
                c++;
        }
        return (Q[i] = r - x);
    }
    

提交回复
热议问题