random.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * @Author : jiejie
  3. * @GitHub : https://github.com/jiejieTop
  4. * @Date : 2021-02-26 12:00:24
  5. * @LastEditors : jiejie
  6. * @LastEditTime : 2022-06-15 19:44:22
  7. * @FilePath : /mqttclient/common/random.c
  8. * Copyright (c) 2022 jiejie, All Rights Reserved. Please keep the author information and source code according to the license.
  9. */
  10. #include <stdlib.h>
  11. #include "random.h"
  12. extern int platform_timer_now();
  13. static unsigned int last_seed = 1;
  14. int __attribute__((weak)) platform_timer_now()
  15. {
  16. return 1;
  17. }
  18. static int do_random(unsigned int seed)
  19. {
  20. srand(seed);
  21. return rand();
  22. }
  23. int random_number(void)
  24. {
  25. unsigned int seed = (unsigned int) platform_timer_now();
  26. last_seed += (seed >> ((seed ^ last_seed) % 3));
  27. return do_random(last_seed ^ seed);
  28. }
  29. // random number range interval [min, max)
  30. int random_number_range(unsigned int min, unsigned int max)
  31. {
  32. return (random_number() % (max - min)) + min;
  33. }
  34. int random_string(char *buffer, int len)
  35. {
  36. unsigned int i, flag, seed, random;
  37. if (NULL == buffer)
  38. return 0;
  39. seed = (unsigned int) random_number();
  40. seed += (unsigned int) ((size_t)buffer ^ seed);
  41. random = (unsigned int)do_random(seed);
  42. for (i = 0; i < len; i++) {
  43. random = do_random(seed ^ random);
  44. flag = (unsigned int)random % 3;
  45. switch (flag) {
  46. case 0:
  47. buffer[i] = 'A' + do_random(random ^ (i & flag)) % 26;
  48. break;
  49. case 1:
  50. buffer[i] = 'a' + do_random(random ^ (i & flag)) % 26;
  51. break;
  52. case 2:
  53. buffer[i] = '0' + do_random(random ^ (i & flag)) % 10;
  54. break;
  55. default:
  56. buffer[i] = 'x';
  57. break;
  58. }
  59. random += ((0xb433e5c6 ^ random) << (i & flag));
  60. }
  61. buffer[len] = '\0';
  62. return len;
  63. }