如何生成定长的随机字符串

其实标题名字起得不是很恰当,主要最近在写代码的时候,需要生成一个全局范围内唯一的一个字符串,该字符串由两部分组成,2位的索引+15位的用户标识。例如这样的08460980000000001。
如果用户标识不存在的时候,需要采用15位的随机字符串代替。针对随机生成字符串的部分,简单写了(抄了)一段代码,

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "time.h"

typedef unsigned char U8;

/* 随机定长length的字符串 */
// 这里只给了buff指针,请在调用处申请好内存,
// 请勿传入空指针,要确保buff size 大于 length
static coid genRandomString(char *buff, U8 length)
{
    U8 metachar[] = "0123456789";
    U8 index	  = 0;
	
    srand((U8)time(NULL)); // 时间为种子
	
    for(index = 0; index < length; index++)
    {
        buff[index] = metachar[rand() % 10];
    }
    buff[length] = '\0';
}
/* 项目中的调用出比较复杂,简单写一个主函数调用一下吧 */
int main()
{
    U8 imsiStr[16]     = {'\0'};
    U8 pfIndex         = 8;
    U8 outString[18]   = {'\0'};
	
    outString[0] = (pfIndex / 10) + '0';
    outString[1] = (pfIndex % 10) + '0';

    genRandomString(imsiStr, 15);
    memcpy(&outString[2], imsiStr, 15);
    printf("outString = %s, strlen = %d\n", outString, strlen(outString));

    return 0;
}

哇哇哇,写好了,很开心对不对,编译执行一下吧,不错,生成了一个值:

outString = 08120035406835352, strlen = 17

貌似很符合要求呀,那我们修改一下代码,

int main()
{
    U8 imsiStr[16]      = {'\0'};
    U8 pfIndex          = 8;
    U8 outString[18]	= {'\0'};
    U8 loop             = 20;
	
    outString[0] = (pfIndex / 10) + '0';
    outString[1] = (pfIndex % 10) + '0';
	
    while(loop)
    {
        genRandomString(imsiStr, 15);
        memcpy(&outString[2], imsiStr, 15);
        printf("outString = %s, strlen = %d\n", outString, strlen(outString));
        loop --;
    }
    return 0;
}

猜猜,会不会生成完全不同的20组字符串,运行一下吧

outString = 08297494622012913, strlen = 17
outString = 08297494622012913, strlen = 17
outString = 08297494622012913, strlen = 17

outString = 08297494622012913, strlen = 17

这是怎么回事。

我们分析一下代码,发现每次执行时,都执行了srand((U8)time(NULL));
因为此程序产生一个随机数之前,都调用一次srand,而由于计算机运行很快,所以每用time得到的时间都是一样 的(time 的时间精度较低,只有55ms)。这样相当于使用同一个种子产生随机序列,所以产生的随机数总是相同的。

我们把seed放在外层就可以,试试吧!

static coid genRandomString(char *buff, U8 length)
{
    U8 metachar[] = "0123456789";
    U8 index	  = 0;
	
    // srand((U8)time(NULL)); // 时间为种子
	
    for(index = 0; index < length; index++)
    {
        buff[index] = metachar[rand() % 10];
    }
    buff[length] = '\0';
}

int main()
{
    U8 imsiStr[16]      = {'\0'};
    U8 pfIndex          = 8;
    U8 outString[18]	= {'\0'};
    U8 loop             = 20;
	
    outString[0] = (pfIndex / 10) + '0';
    outString[1] = (pfIndex % 10) + '0';
	
    srand((U8)time(NULL)); // 时间为种子
	
    while(loop)
    {
        genRandomString(imsiStr, 15);
	
        memcpy(&outString[2], imsiStr, 15);
	
        printf("outString = %s, strlen = %d\n", outString, strlen(outString));
        loop --;
    }
    return 0;
}

enjoy it!

猜你喜欢

转载自blog.csdn.net/hitguolu/article/details/84134754