使用C语言生成任意指定长度的一串随机数
在写程序或者测试的时候,有时候需要一些随机数。
类似的随机数生成程序,我不知道写过多少次,每次写完后都“用完就扔”。
为了方便自己以后的使用,特在这片博文中记录下来代码。
/* function: sometimes you will need a random sequence number usage: ./rand LENGTH */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define DEFAULT_SIZE 32 // 默认生成长度 #define MOD_NUMBER 256 #define COLUMN_WIDTH 16 // 每行输出的数字个数 int main(int argc, char *argv[]) { int seq_size = 0; int seed = 0; if (argc == 2) { seq_size = atoi(argv[1]); } else { seq_size = DEFAULT_SIZE; } // incase that atoi() get invalid input if (seq_size <= 0) { seq_size = DEFAULT_SIZE; } // generate randome seed seed = (int)time(NULL); srand(seed); printf("length = %d seed = %d\n", seq_size, seed); printf("unsigned char data[%d] = { \n ", seq_size); int cur_num = 0; int before_tail_pos = seq_size - 1; for (int i = 0; i < seq_size; i++) { cur_num = rand() % MOD_NUMBER; if (i == before_tail_pos) { printf("0x%02x\n", cur_num); }else if (0 == ((i + 1) % COLUMN_WIDTH)) { printf("0x%02x,\n ", cur_num); } else { printf("0x%02x, ", cur_num); } } printf("};\n"); return 0; }
运行截图1:
运行截图2: