test01 发表于 2012-9-21 00:12:29

贡献一个开源的“真随机数”发生函数

本帖最后由 test01 于 2012-11-3 01:46 编辑

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <stdlib.h>

void generating_random_seed (uint_fast16_t seed_width, uint16_t seed_bits[])//Occupied A7 pin. Arduino with the statement.
{
const uint_fast16_t MAX_WIDTH = 256;
const uint_fast8_t NOISE_INPIT_PIN = A7;

if ((seed_width <= 0) and (seed_width > MAX_WIDTH))
{
    return;
}

analogReference(INTERNAL);//Arduino with the statement
uint_fast8_t analog_bit_n0, analog_bit_n1;
uint16_t analog_bits;
int_fast8_t n = 0;
analog_bit_n0 = read_bit(analogRead(NOISE_INPIT_PIN), 16, 0);//Arduino with the statement
while (n < 16)
{
    analog_bit_n1 = read_bit(analogRead(NOISE_INPIT_PIN), 16, 0);//Arduino with the statement
    if (analog_bit_n0 not_eq analog_bit_n1)
    {
      analog_bits = xor_bit(analog_bits, 16, n, (analog_bit_n0 > analog_bit_n1) ? 0 : 1);
      analog_bit_n0 = read_bit(analogRead(NOISE_INPIT_PIN), 16, 0);//Arduino with the statement
      ++n;
    }
    else
    {
      analog_bit_n0 = analog_bit_n1;
    }
}
srand(analog_bits);

const uint16_t WORD_10 = (((uint16_t)B10101010) << 8) | B10101010;
const uint16_t WORD_01 = compl WORD_10;
const uint16_t WORD_11 = compl((uint16_t)0);
div_t array_length = div(seed_width - 1, 16);
uint16_t initialization_bits;
((rand() % 2) == 0) ? initialization_bits = WORD_10 : initialization_bits = WORD_01;
for (int_fast8_t i = 0; i <= array_length.quot; ++i)
{
    seed_bits = initialization_bits;
}
seed_bits and_eq compl(WORD_11 << (array_length.rem + 1));

analog_bit_n0 = read_bit(analogRead(NOISE_INPIT_PIN), 16, 0);//Arduino with the statement
for (int_fast16_t i = (int_fast16_t)seed_width * 3 - 1; i >= 0; --i)
{
    ldiv_t seed_pointer = ldiv((int_fast32_t)seed_width * rand() / ((uint_fast16_t)RAND_MAX + 1), 16);
    analog_bit_n1 = read_bit(analogRead(NOISE_INPIT_PIN), 16, 0);//Arduino with the statement
    if (analog_bit_n0 not_eq analog_bit_n1)
    {
      seed_bits = xor_bit(seed_bits, 16, seed_pointer.rem, (analog_bit_n0 > analog_bit_n1) ? 0 : 1);
      analog_bit_n0 = read_bit(analogRead(NOISE_INPIT_PIN), 16, 0);//Arduino with the statement
    }
    else
    {
      analog_bit_n0 = analog_bit_n1;
    }
}
}
===========================
说明:这用了A7模拟输入脚,让A7接一根悬空的长引线效果好
可生成1位到256位的真随机数
注意,受avr里的adc所限,产生的随机数如果要用在质量要求高的应用,一定先行检验是否符合要求
欢迎大家来检验这个发生器的随机性

迷你强 发表于 2012-9-21 16:01:05

{:soso_e103:},好东西。。。改天抽样测评下。。

test01 发表于 2012-9-22 01:32:40

修正一个bug,65行里是ldiv_t和ldiv,不是div_t和div

test01 发表于 2012-10-13 02:47:37

为更方便大家应用,变更了开源许可证

迷你强 发表于 2012-10-14 08:33:49

:D

test01 发表于 2012-11-3 01:47:04

晕死
漏写了#include <stdlib.h>
页: [1]
查看完整版本: 贡献一个开源的“真随机数”发生函数