简体   繁体   English

在C中生成随机字符串unsigned char

[英]Generating random string unsigned char in C

I want to generate a random string text of length 100 with the code below, then to verify that I print the length of the variable text but sometimes that is less than 100. How can I fix that? 我想用下面的代码生成长度为100的随机字符串文本,然后验证我是否打印了变量文本的长度,但有时小于100.如何解决这个问题?

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

int main() {
    int i, LEN = 100;
    srandom(time(NULL));
    unsigned char text[LEN];
    memset(text, 1, LEN);
    for (i = 0; i < LEN; i++) {
        text[i] = (unsigned char) rand() & 0xfff;
    }
    printf("plain-text:");
    printf("strlen(text)=%zd\n", strlen(text));

}

Perhaps a random character 0 was added to the string, and then it is considered as the end of string by strlen . 也许随机字符0被添加到字符串中,然后它被strlen视为字符串的结尾。

You can generate random characters as (rand() % 255) + 1 to avoid zeros. 您可以生成随机字符(rand() % 255) + 1以避免零。

And at the end you have to zero-terminate the string. 最后你必须对字符串进行零终止。

LEN = 101; // 100 + 1
....
for (i = 0; i < LEN - 1; i++) {
    text[i] = (unsigned char) (rand() % 255 + 1);
}
text[LEN-1] = 0;

I want to generate a random string text of length 100 with the code below, then to verify that I print the length of the variable text but sometimes that is less than 100. How can I fix that? 我想用下面的代码生成长度为100的随机字符串文本,然后验证我是否打印了变量文本的长度,但有时小于100.如何解决这个问题?

  1. First of all, if you want to generate a string of length 100, you'll need to declare an array of size 101. 首先,如果要生成长度为100的字符串,则需要声明一个大小为101的数组。

     int i, LEN = 101; srandom(time(NULL)); unsigned char text[LEN]; 
  2. When you are assigning the characters from the call to rand , make sure that it is not 0 , which is usually the null terminator for strings. 当您将调用中的字符分配给rand ,请确保它不是0 ,这通常是字符串的空终止符。

     for (i = 0; i < LEN - 1; /* Don't increment i here */) { c = (unsigned char) rand() & 0xfff; if ( c != '\\0' ) { text[i] = c; // Increment i only for this case. ++i } } 

    and don't forget to null terminate the string. 并且不要忘记null终止字符串。

     text[LEN-1] = '\\0'; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM