这是在 C 或 C++ 中生成随机字节数组的好方法吗?
Is this a good approach to random byte array genaration in C or C++?
我知道这里已经讨论过这种问题:如何在 C 中生成随机数?
但我想分享我实现它的方式,只是为了了解人们可能会怎么想它。
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
long int getNanoSecs(){
struct timespec unixtimespec;
clock_gettime(CLOCK_REALTIME_COARSE, &unixtimespec);
return unixtimespec.tv_nsec;
}
...
unsigned char personal_final_token[PERSONAL_FINAL_TOKEN_SIZE_SIZE];
unsigned char pwd_ptr_ctr;
srandom(getNanoSecs()*(getNanoSecs()&0xFF));
for(pwd_ptr_ctr=0;pwd_ptr_ctr<PERSONAL_FINAL_TOKEN_SIZE_SIZE;pwd_ptr_ctr++){
memset(personal_final_token+pwd_ptr_ctr,(random()^getNanoSecs())&0xFF,1);
}
只需定义PERSONAL_FINAL_TOKEN_SIZE_SIZE,您就可以生成所需大小的随机令牌。
小心你的时钟源,否则你可能会得到意想不到的结果:
#include <stdio.h>
#include <linux/time.h>
#define SAMPLES 10
long getNanoSecs(){
struct timespec unixtimespec;
clock_gettime(CLOCK_REALTIME_COARSE, &unixtimespec);
return unixtimespec.tv_nsec;
}
int main (int argc, char* argv[]) {
int i;
long clocks[SAMPLES];
for (i = 0; i < SAMPLES; i++)
clocks[i] = getNanoSecs();
for (i = 0; i < SAMPLES; i++)
printf("%lun", getNanoSecs());
return 0;
}
[tbroberg@www src]$ ./a.out727544983728544969728544969728544969728544969728544969728544969728544969728544969728544969
你绝对是对的,我想补充一点,我修改了CLOCK_REALTIME_COARSE
CLOCK_REALTIME
根据Linux人:
"CLOCK_REALTIME测量实际(即挂钟(时间的系统范围时钟。设置此时钟需要适当的权限。 该时钟受到系统时间不连续跳跃(例如,如果系统管理员手动更改时钟(以及 adjtime(3( 和 NTP 执行的增量调整的影响。
CLOCK_REALTIME_COARSE(从 Linux 2.6.32 开始;特定于 Linux(CLOCK_REALTIME的更快但不太精确的版本。 当您需要非常快速但不是细粒度的时间戳时,请使用。
但是谢谢你的YOUR_TIME :)
相关文章:
- 输出没有重复元素的动态数组(收缩数组)C++
- 将字符串转换为无符号字符数组/字节数组
- 检查彩虹数组(检查数组的反向样式是否与自身匹配)
- 如何创建对齐的数组 c++ 数组?
- 查找数组中数组元素的重复出现?
- C++释放带有子数组的数组的内存分配
- 返回一个数组,该数组包含数组中的数量,该数组数量较小或等于给定数组中的元素
- 通过键盘输入字符串数组和 int 数组的数组大小
- 如何在C 中创建类似于Python的Numpy数组的数组
- 无法获取数组内数组的总和
- C4838 警告,包含常量字符* 数组的数组初始化
- 连接数组,数组 1 内存消失C++
- 如何在C++中创建二维数组的数组
- 获取字符数组C++数
- 2D数组中数组下标的类型"int[int]"无效
- C 模板类动态数组的数组到数组
- 结构数组的数组
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- 对象的数组-STD ::数组 - 构造函数初始化问题
- 使用SSE内部函数将布尔数组(8字节布尔)转换为int或char