You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.6KB

  1. // Copyright 2009 Olivier Gillet.
  2. //
  3. // Author: Olivier Gillet (ol.gillet@gmail.com)
  4. //
  5. // This program is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. //
  16. // -----------------------------------------------------------------------------
  17. //
  18. // Fast 16-bit pseudo random number generator.
  19. #ifndef AVRLIB_RANDOM_H_
  20. #define AVRLIB_RANDOM_H_
  21. #include "avrlib/base.h"
  22. namespace avrlib {
  23. class Random {
  24. public:
  25. static void Update() {
  26. // Galois LFSR with feedback polynomial = x^16 + x^14 + x^13 + x^11.
  27. // Period: 65535.
  28. rng_state_ = (rng_state_ >> 1) ^ (-(rng_state_ & 1) & 0xb400);
  29. }
  30. static inline uint16_t state() { return rng_state_; }
  31. static inline void Seed(uint16_t seed) {
  32. rng_state_ = seed;
  33. }
  34. static inline uint8_t state_msb() {
  35. return static_cast<uint8_t>(rng_state_ >> 8);
  36. }
  37. static inline uint8_t GetByte() {
  38. Update();
  39. return state_msb();
  40. }
  41. static inline uint16_t GetWord() {
  42. Update();
  43. return state();
  44. }
  45. private:
  46. static uint16_t rng_state_;
  47. DISALLOW_COPY_AND_ASSIGN(Random);
  48. };
  49. } // namespace avrlib
  50. #endif // AVRLIB_RANDOM_H_