gpt4 book ai didi

c - 在 C 中将数字分配给 char 变量?

转载 作者:行者123 更新时间:2023-11-30 19:57:13 32 4
gpt4 key购买 nike

我计划将数字数据类型分配给 char 变量。代码将是这样的:

#include <stdlib.h>
#include <stdio.h>

typedef unsigned short ushort;
typedef unsigned u;

ushort getRandomNumber(){
return (ushort)(rand() % 9);
}

ushort getASCII(char Char) {
return (ushort)Char;
}

char getRandomChar() {
ushort chance = (rand() % 2) + 1;
const ushort aASCII = 97 , zASCII = 122 , AASCII = 65 , ZASCII = 89;
if(chance == 1)
return (char)(aASCII + (rand() % (zASCII - aASCII)));
else
return (char)(AASCII + (rand() % (ZASCII - AASCII)));
}

int main(void) {
srand(time(NULL));
ushort size;
puts("Enter password size : " );
fflush(stdout);
scanf("%i" , &size);
if(size >= 4) {
char Password[size + 1];
for(ushort i = 1 ; i <= size ; ++i){
ushort chance = (rand() % 2) + 1;
if(chance == 1)
Password[i] = getRandomChar();
else
Password[i] = getRandomNumber();

}
printf("%s" , Password);
return EXIT_SUCCESS;
}
else {
puts("Error. Try again");
}
}

它不会返回任何错误,但会打印与 ASCII 代码匹配的字符。所以这段代码不是正确的。

原始代码是一个随 secret 码生成器,据我所知,它不是很好也不安全。随机数在输出中显示为 ASCII 字符。

我在 Google 上进行了搜索,但没有找到有用的结果。仅this但这是相反的过程。其命令/算法是什么?

感谢您的帮助。

编辑:这里的问题是我将 int 分配给包含我不想显示为数字的字符的字符数组。

最佳答案

由于您实际上要做的是用字母或单个数字填充字符串,因此您实际上不想存储数字本身,而是存储数字的 ASCII 代码。

您可以按如下方式执行此操作:

ushort getRandomNumber(){
return '0' + (ushort)(rand() % 10);
}

请注意 ASCII 代码使用字符常量而不是“魔数(Magic Number)”。您可以在获取角色时进行类似的更改:

char getRandomChar() {
ushort chance = (rand() % 2) + 1;
if(chance == 1)
return 'a' + (rand() % ('z'- 'a' + 1));
else
return 'a' + (rand() % ('Z' - 'A' + 1));
}

无论使用何种字符编码,C 标准都保证 0 - 9 的数字是连续的。然而,对于信件来说,这种保证存在。

您可以通过创建一个包含所有要使用的字符的数组并在该数组中索引以获得给定的随机字符来进一步简化逻辑:

char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for(ushort i = 1 ; i <= size ; ++i){
Password[i] = characters[rand() % sizeof(characters)];
}
Password[i] = 0;

关于c - 在 C 中将数字分配给 char 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51290872/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com