在寫程序或者測試的時候,有時候需要一些隨機數。
類似的隨機數生成程序,我不知道寫過多少次,每次寫完后都“用完就扔”。
為了方便自己以后的使用,特在這片博文中記錄下來代碼。
/* 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: