Pseudorandom generator in Assembly Language

前端 未结 9 1023
予麋鹿
予麋鹿 2021-01-05 11:07

I need a pseudorandom number generator algorithm for a assembler program assigned in a course, and I would prefer a simple algorithm. However, I cannot use an external libra

相关标签:
9条回答
  • 2021-01-05 11:49

    Well - Since I haven't seen a reference to the good old Linear Feedback Shift Register I post some SSE intrinsic based C-Code. Just for completenes. I wrote that thing a couple of month ago to sharpen my SSE-skills again.

    #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));
    }
    

    Translating this code to assembler is trivial. Just replace the intrinsics with the real SSE instructions and add a loop around it.

    Btw - the sequence this code genreates repeats after 4.61169E+18 numbers. That's a lot more than you'll get via the prime method and 32 bit arithmetic. If unrolled it's faster as well.

    0 讨论(0)
  • 2021-01-05 11:49

    also you probably can emulate shifting register with XOR sum elements between separate bits, which will give you pseudo-random sequence of numbers.

    0 讨论(0)
  • 2021-01-05 11:52

    Volume 2 of The Art of Computer Programming has a lot of information about pseudorandom number generation. The algorithms are demonstrated in assembler, so you can see for yourself which are simplest in assembler.

    If you can link to an external library or object file, though, that would be your best bet. Then you could link to, e.g., Mersenne Twister.

    Note that most pseudorandom number generators are not safe for cryptography, so if you need secure random number generation, you need to look beyond the basic algorithms (and probably should tap into OS-specific crypto APIs).

    0 讨论(0)
提交回复
热议问题