mercredi 26 septembre 2018

Simplest random number generator without C library?

I would need to add some randomization to my Cortex M0 CPU firmware. The randomness is not important but the speed is.

I tested two functions I found online. With random() I managed to generate 1 number per 31 clock cycles, while random_uint generated 1 number in 20 cycles. My target is less than 10. What are other functions can I use?

unsigned random()
{
    unsigned b;

    b = t1 ^ (t1 >> 2) ^ (t1 >> 6) ^ (t1 >> 7);
    t1 = (t1 >> 1) | (~b << 31);

    b = (t2 << 1) ^ (t2 << 2) ^ (t1 << 3) ^ (t2 << 4);
    t2 = (t2 << 1) | (~b >> 31);

    return t1 ^ t2;
}



unsigned random_uint() {
    m_z = 36969 * (m_z & 65535) + (m_z >> 16);
    m_w = 18000 * (m_w & 65535) + (m_w >> 16);
    return (m_z << 16) + m_w;
}




Aucun commentaire:

Enregistrer un commentaire