Advertisement
Kaelygon

8-bit PRNG

Jun 26th, 2024
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. // rngtest < ./rand
  2. // ./rand | dieharder -B -g 200 -a
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <stdint.h>
  6. #include <math.h>
  7.  
  8.  
  9. int main() {
  10.  
  11. //starting number and table indices
  12. uint8_t num = 43;
  13. uint8_t a=131;
  14. uint8_t b=73;
  15.  
  16. //bit width
  17. const uint8_t bw = sizeof(num)*8;
  18.  
  19. //tables of random numbers
  20. uint8_t atab[] = {
  21. 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53
  22. };
  23.  
  24. uint8_t btab[] = {
  25. 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131
  26. };
  27.  
  28. //number of elements in the tables (must be power of two that we can avoid expensive modulus)
  29. const uint8_t elems=sizeof(atab)/sizeof(atab[0]);
  30.  
  31. while(1){
  32. a = (a+num&(elems-1)) & (elems-1); //use 'num' to set a index
  33. b = (b+1 ) & (elems-1); //b index increments by 1 and loops
  34.  
  35. //swap elements
  36. uint8_t buf = atab[a];
  37. atab[a]=btab[b]+num; //add num for additional mixing
  38. btab[b]=buf;
  39.  
  40. uint8_t shift = a&(bw-1); //right shift amount
  41.  
  42. num = (num>>shift) | (num<<(bw-shift)); //ror
  43. num = num ^ atab[a] + btab[b]; //mixing
  44.  
  45. fwrite(&num, sizeof(uint8_t), 1, stdout); //write
  46. }
  47.  
  48. return 0;
  49.  
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement