implementation of rand()

后端 未结 11 1472
遥遥无期
遥遥无期 2020-12-01 01:34

I am writing some embedded code in C and need to use the rand() function. Unfortunately, rand() is not supported in the library for the controller. I need a simple implement

11条回答
  •  情书的邮戳
    2020-12-01 02:22

    Use the C code for LFSR113 from L'écuyer:

    unsigned int lfsr113_Bits (void)
    {
       static unsigned int z1 = 12345, z2 = 12345, z3 = 12345, z4 = 12345;
       unsigned int b;
       b  = ((z1 << 6) ^ z1) >> 13;
       z1 = ((z1 & 4294967294U) << 18) ^ b;
       b  = ((z2 << 2) ^ z2) >> 27; 
       z2 = ((z2 & 4294967288U) << 2) ^ b;
       b  = ((z3 << 13) ^ z3) >> 21;
       z3 = ((z3 & 4294967280U) << 7) ^ b;
       b  = ((z4 << 3) ^ z4) >> 12;
       z4 = ((z4 & 4294967168U) << 13) ^ b;
       return (z1 ^ z2 ^ z3 ^ z4);
    }
    

    Very high quality and fast. Do NOT use rand() for anything. It is worse than useless.

提交回复
热议问题