【问题标题】:Generating random string unsigned char in C在C中生成随机字符串无符号字符
【发布时间】:2015-04-27 08:58:50
【问题描述】:

我想用下面的代码生成一个长度为 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));

}

【问题讨论】:

  • 如果您还不熟悉 ascii,您可能想了解一下,有很多 ascii 代码不是非典型字符串
  • 注:text[i] = (unsigned char) rand() &amp; 0xfff;text[i] = ((unsigned char) rand()) &amp; 0xfff;不一样吗?那么为什么&amp; 0xfff
  • 小点:1) Unix srandom()random() 一起使用,std C srand()rand() 一起使用。 2) 考虑size_t LEN 而不是int

标签: c


【解决方案1】:

可能是随机字符0被添加到字符串中,然后被strlen认为是字符串的结尾。

您可以生成随机字符为(rand() % 255) + 1 以避免零。

最后你必须以零结尾的字符串。

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

【讨论】:

    【解决方案2】:

    我想用下面的代码生成一个长度为 100 的随机字符串文本,然后验证我打印了变量文本的长度,但有时它小于 100。我该如何解决这个问题?

    1. 首先,如果要生成长度为 100 的字符串,则需要声明一个大小为 101 的数组。

      int i, LEN = 101;
      srandom(time(NULL));
      unsigned char text[LEN];
      
    2. 当您将调用中的字符分配给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
          }
      }
      

      并且不要忘记空终止字符串。

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

    【讨论】:

    • 通过不使用% some non-power-of-2,这种方法避免了轻微的bias。 +1。
    猜你喜欢
    • 2012-04-17
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2011-06-30
    • 1970-01-01
    相关资源
    最近更新 更多