shr3.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * SHR3 - Pseudo random number generator
  3. *
  4. * http://groups.google.com/group/sci.math/msg/9959175f66dd138f
  5. * http://groups.google.com/group/sci.math/msg/7e499231fb1e58d3
  6. *
  7. * Copyright (c) 2020 Michael Buesch <m@bues.ch>
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License along
  20. * with this program; if not, write to the Free Software Foundation, Inc.,
  21. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. */
  23. #include "bitops.h"
  24. #include "compat.h"
  25. #include "shr3.h"
  26. #include "util.h"
  27. static uint32_t shr3_state;
  28. uint8_t shr3_get_random_bits(uint8_t nr_of_bits)
  29. {
  30. uint32_t y = shr3_state;
  31. uint8_t ret = 0u;
  32. while (nr_of_bits > 0u) {
  33. y ^= y << 13;
  34. y ^= y >> 17;
  35. y ^= y << 5;
  36. ret = (uint8_t)(ret << 1u);
  37. ret = (uint8_t)(ret | (uint8_t)(y & 1u));
  38. nr_of_bits--;
  39. }
  40. shr3_state = y;
  41. return ret;
  42. }
  43. uint8_t shr3_get_random_value8(uint8_t min_value, uint8_t max_value)
  44. {
  45. uint8_t range, nr_of_bits, value;
  46. if (min_value >= max_value)
  47. return min_value;
  48. range = (uint8_t)(max_value - min_value);
  49. nr_of_bits = fls8(range);
  50. do {
  51. value = shr3_get_random_bits(nr_of_bits);
  52. } while (value > range);
  53. value = (uint8_t)(value + min_value);
  54. return value;
  55. }
  56. void shr3_init(uint32_t seed)
  57. {
  58. shr3_state = seed ? seed : 0x7FFFFFFFu;
  59. }