home *** CD-ROM | disk | FTP | other *** search
/ Computer Select (Limited Edition) / Computer Select.iso / dobbs / v17n02 / random.asc < prev    next >
Encoding:
Text File  |  1991-12-17  |  1.9 KB  |  47 lines

  1. _PSEUDO-RANDOM SEQUENCE GENERATOR FOR 32-BIT CPUs_
  2. by Bruce Schneier
  3.  
  4.  
  5. [LISTING ONE]
  6.  
  7.  
  8. int RANDOM ()  {
  9.     static unsigned long register; /*Register must be unsigned so right 
  10.                                      shift works properly.*/
  11.     /*Register should be initialized with some random value.*/
  12.     register = ((((register >> 31) /*Shift the 32nd bit to the first bit*/
  13.                ^ (register >> 6)   /*XOR it with the seventh bit*/
  14.                ^ (register >> 4)   /*XOR it with the fifth bit*/
  15.                ^ (register >> 2)   /*XOR it with the third bit*/
  16.                ^ (register >> 1)   /*XOR it with the second bit*/
  17.                ^ register)         /*and XOR it with the first bit.*/
  18.                & 0x0000001)        /*Strip all the other bits off and*/
  19.                <<31)               /*move it back to the 32nd bit.*/
  20.                | (register >> 1);  /*Or with the register shifted right.*/
  21.     return register & 0x00000001;  /*Return the first bit.*/
  22. }
  23.  
  24.  
  25.  
  26.  
  27. [LISTING TWO]
  28.  
  29.  
  30. int VERYRANDOM ()  {
  31.     static unsigned long regA, regB, regC;
  32.     /*regA, regB, and regC should be initialized with some random value.*/
  33.     regA = ((((regA>>31)^(regA>>6)^(regA>>4)^(regA>>2)^(regA<<1)^regA)
  34.            & 0x00000001)<<31) | (regA>>1);
  35.     regB = ((((regB>>30)^(regB>>2)) & 0x00000001)<<30) | (regB>>1);
  36.     regC = ((((regC>>28)^(regC>>1)) & 0x00000001)<<28) | (regC>>1);
  37.     /*regB is a 31-bit LFSR.  regC is a 29-bit LFSR.*/
  38.     /*Both feedback sequences are chosen to be maximum length.*/
  39.     return ((regA & regB) | (!regA & regC)) & 0x00000001;
  40.     /*Above is equivalant to:  if A then return B else return C.*/
  41.      /* Variants:  return ((regA & regB) | (regA & regC) | (regB & regC)) & 
  42.        0x00000001; Above variant returns the majority of A, B, and C.
  43.        return (regA ^ regB ^ regC) & 0x00000001;
  44.        Above variant returns the XOR of A, B, and C.  */  
  45. }
  46.  
  47.