码迷,mamicode.com
首页 > 编程语言 > 详细

一个简单的伪随机数发生算法(转)

时间:2017-09-07 11:02:12      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:logs   bbs   none   div   value   void   forum   自己   note   

源:一个简单的伪随机数发生算法

//此代码纯属交流目的,如用作安全领域,后果自负

#include <stdint.h>
#include <stdlib.h>


//! \brief random seed
static uint16_t s_hwRandomSeed = 0xAA55;
static uint8_t s_chRandomTable[] = {
                0x12,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF,
                0xF1,0xE2,0xD3,0xC4,0xB5,0xA6,0x97,0x88};


/*! \note set random generator seed 
*  \param hwSeed random seed
*  \return none
*/
void set_random_seed( uint16_t hwSeed )
{
    s_hwRandomSeed ^= hwSeed;
}

/*! \note get a random integer
*  \param none
*  \return random integer value
*/
uint16_t get_random_u16( void )
{
    uint16_t *phwResult = (uint16_t *)&s_chRandomTable[(s_hwRandomSeed & 0x0E)];
    
    *phwResult += s_hwRandomSeed;
    s_hwRandomSeed ^= *phwResult;
    
    return *phwResult;
}

/*! \note get a random byte
*  \param none
*  \return random integer value
*/
uint8_t get_random_u8( void )
{
    return get_random_u16();
}

 

/*
最常用的随机算法,C语言标准库函数的结果和这个一致
这里是32位机用的,8位机自己加UL,改int为long
*/

int seed;

void srand(int s)
{
    seed = s;
}

int rand()
{
    seed = seed * 22695477 + 1;
}

 

一个简单的伪随机数发生算法(转)

标签:logs   bbs   none   div   value   void   forum   自己   note   

原文地址:http://www.cnblogs.com/LittleTiger/p/7488446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!