# [nRF51822] 16、nRF51822的随机数生成器，及随机数生成器的一些知识（可以帮您补补随机数发生器的知识）

#### 2、伪随机数发生器

 1 #include <iostream>
2 #include <ctime>
3 #include <cstdlib>
4 using namespace std;
5
6 int main()
7 {
8     double random(double,double);
9     srand(unsigned(time(0)));
10     for(int icnt = 0; icnt != 10; ++icnt)
11         cout << "No." << icnt+1 << ": " << int(random(0,10))<< endl;
12     return 0;
13 }
14
15 double random(double start, double end)
16 {
17     return start+(end-start)*rand()/(RAND_MAX + 1.0);
18 }
19 /* 运行结果
20 * No.1: 3
21 * No.2: 9
22 * No.3: 0
23 * No.4: 9
24 * No.5: 5
25 * No.6: 6
26 * No.7: 9
27 * No.8: 2
28 * No.9: 9
29 * No.10: 6
30 */

#### 5、nRF51822的随机数发生器

nRF51822_Product Specification_v3.1.pdf中介绍nrf自带真随机生成器：
The Random Number Generator (RNG) generates true non-deterministic random numbers derived from thermal noise that are suitable for cryptographic purposes. The RNG does not require a seed value.

The random number generator (RNG) driver includes two layers: the hardware access layer (HAL) and the driver layer (DRV).
The hardware access layer provides basic APIs for accessing the registers of the random number generator. See the API documentation for the RNG HAL and driver for details.
The driver layer provides APIs on a higher level than the HAL. See the API documentation for the RNG driver for details.

The Random Number Generator Example provides sample code that you can use to quickly get started.

 1 /** @brief Function for getting vector of random numbers.
2 *
3 * @param[out] p_buff Pointer to unit8_t buffer for storing the bytes.
4 * @param[in] length Number of bytes to take from pool and place in p_buff.
5 *
6 * @retval Number of bytes actually placed in p_buff.
7 */
8 uint8_t random_vector_generate(uint8_t *p_buff, uint8_t size)
9 {
10     uint8_t available;
11     uint32_t err_code;
12     err_code = nrf_drv_rng_bytes_available(&available);
13     APP_ERROR_CHECK(err_code);
14     uint8_t length = (size < available) ? size : available;
15     err_code = nrf_drv_rng_rand(p_buff, length);
16     APP_ERROR_CHECK(err_code);
17     return length;
18 }

+ 订阅