Golang编程语言知识介绍


  • 首页

  • todo

  • 思考

  • life

  • food

  • OS

  • lua

  • redis

  • Golang

  • C

  • TCP/IP

  • ebpf

  • p4

  • OpenVPN

  • IPSec

  • L2TP

  • DNS

  • distributed

  • web

  • OpenWRT

  • 运维

  • Git

  • 鸟哥的私房菜

  • IT杂谈

  • 投资

  • About Me

  • 友情链接

  • FTP

  • 搜索
close

C语言 获取随机数

时间: 2023-09-21   |   分类: c     |   阅读: 534 字 ~2分钟

srand()和rand()

声明

#include <stdlib.h>
int rand(void);
int rand_r(unsigned int *seedp);	//线程安全版本
void srand(unsigned int seed);

实例

#include <stdlib.h>
#include <stdio.h>
#include <time.h> 

int main()
{ 
	srand((unsigned)time(NULL)); 
	for(int i = 0; i < 10;i++ ) 
		printf("%d = %u\n",i,rand());

	return 0;
}

二次随机

srand((unsigned)time(NULL));
int RanMe1 = rand() % 1000000;
srand(RanMe1);
int RanMe2 = rand() % 1000000;

srandom()和random()

声明

#include <stdlib.h>
long int random(void);
void srandom(unsigned int seed);
int random_r(struct random_data *buf, int32_t *result);
int srandom_r(unsigned int seed, struct random_data *buf);

实例

#include <stdlib.h>
#include <stdio.h>
#include <time.h> 

int main()
{ 
	srandom(time(0));
	for(int i = 0; i < 10;i++ ) 
		printf("%d = %u\n",i,random());
	return 0;
}

rand 与random的区别

https://blog.csdn.net/iicyl/article/details/60603092

/dev/random 或 /dev/urandom

在 Unix 类的系统上,请使用合规随机数生成器,例如 /dev/random 或 /dev/urandom;在 Windows 上,请使用 CNG (Cryptography API: Next Generation)。

https://blog.csdn.net/weixin_38239856/article/details/81979959

区别

  • /dev/random的random依赖于系统中断,因此在系统的中断数不足时,/dev/random设备会一直封锁,尝试读取的进程就会进入等待状态,直到系统的中断数充分够用, /dev/random设备可以保证数据的随机性。
  • /dev/urandom不依赖系统的中断,也就不会造成进程忙等待,但是数据的随机性也不高。

实例

#include <stdlib.h>
#include <stdio.h>
#include <time.h> 
#include <limits.h> 
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

/*
 * 功能:获取字符随机数
 * 参数:int block:类型
 */
int getRandomBytes(char *buf, int length, int block)
{
    int fd, sofar, rc;

    fd = open((block) ? "/dev/random" : "/dev/urandom", O_RDONLY, 0666);
    if (fd < 0) {
        return -1;
    }

    sofar = 0;
    do {
        rc = (int) read(fd, &buf[sofar], length);
        if (rc < 0) {
            close(fd);
            return -2;
        }
        length -= rc;
        sofar += rc;
    } while (length > 0);
    close(fd);
    return 0;
}

int main()
{ 
	int i;
    unsigned int uvalue = 0;
    int data[16];
    if(0 > getRandomBytes((char *)data, sizeof(data), 0))
    {
        printf("getRandomBytes failed!!!\n");
    }
    for (i = 0; i < sizeof(data) / sizeof(int); i++) {
        uvalue += data[i];
    }
    printf("uvalue = %u\n",uvalue);

    return 0;
}

相关内容转载自本链接

#c#
sendmsg 和 recvmsg 函数
天涯论坛KK关于房价评价
shankusu2017@gmail.com

shankusu2017@gmail.com

日志
分类
标签
GitHub
© 2009 - 2025
粤ICP备2021068940号-1 粤公网安备44011302003059
0%