Random Number Generator

B91eae75cd6245bd8074bd0c3f1cc495
0
Nils_Pipenbrinck 101 Mar 21, 2008 at 22:03

Hi folks.

As a little exercise in SSE2 programming I wrote a little random number generator based on a linear feedback shift register of 62 bit length.

It is a bit slower than the standard library rand-function and useless for cryptographical uses, but it has a much larger sequence of random numbers.

The sequence repeats at 4.61169E+18 numbers.

Here it is the code - in case someone ever needs such a thing. It’s written for MSVC.

#include <emmintrin.h>

static __m128i LFSR;

void InitRandom (int Seed)
{
  LFSR = _mm_cvtsi32_si128 (Seed);
}

int GetRandom (int NumBits)
{
  __m128i seed = LFSR;
  __m128i one  = _mm_cvtsi32_si128(1);
  __m128i mask; 
  int i;

  for (i=0; i<NumBits; i++)
  {

    // generate xor of adjecting bits
    __m128i temp = _mm_xor_si128(seed, _mm_srli_epi64(seed,1));

    // generate xor of feedback bits 5,6 and 62,61
    __m128i NewBit = _mm_xor_si128( _mm_srli_epi64(temp,5),
                                    _mm_srli_epi64(temp,61));

    // Mask out single bit: 
    NewBit = _mm_and_si128 (NewBit, one);

    // Shift & insert new result bit:
    seed = _mm_or_si128 (NewBit, _mm_add_epi64 (seed,seed));
  }

  // Write back seed...
  LFSR = seed;

  // generate mask of NumBit ones.
  mask = _mm_srli_epi64 (_mm_cmpeq_epi8(seed, seed), 64-NumBits);

  // return random number:
  return _mm_cvtsi128_si32 (_mm_and_si128(seed,mask));
}

0 Replies

Please log in or register to post a reply.

No replies have been made yet.