随机 int 1-255 到 C 中的字符
我有一个返回 1 到 255 之间整数的函数。有没有办法将此 int 转换为字符,我可以将 strcmp()
转换为现有字符串。
基本上,我需要从 PRNG 创建一串字母(所有 ASCII 值)。除了 int 到 char 部分之外,我已经完成了所有工作。没有像 PHP 中那样的 Chr()
函数。
I have a function that returns an integer, between 1 and 255. Is there a way to turn this int into a character I can strcmp()
to an existing string.
Basically, I need to create a string of letters (all ASCII values) from a PRNG. I've got everything working minus the int to char part. There's no Chr()
function like in PHP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C 中的
char
只能采用CHAR_MIN
到CHAR_MAX
之间的值。如果char
有符号,CHAR_MAX
可能小于 255(例如,常见值为 127)。如果char
是无符号的,CHAR_MAX
必须至少为 255。假设您的
char
是无符号的,您可以将随机数分配给 < code>char (例如在您的字符串中)。如果char
有符号,你必须更加小心。在这种情况下,您可能希望将值 mod 128 分配给您的char
。事实上,由于您正在处理 ASCII,您可能无论如何都想这样做(ASCII 最多只能达到 127)。
最后,强制性的可移植性说明:如果底层编码不是 ASCII,则
char
的整数值可能无法表示其 ASCII 值(例如 EBCDIC)。A
char
in C can only take values fromCHAR_MIN
toCHAR_MAX
. Ifchar
is signed,CHAR_MAX
may be less than 255 (for example, a common value is 127). Ifchar
is unsigned,CHAR_MAX
has to be at least 255.Assuming your
char
is unsigned, you can just assign the random number to achar
(in your string for example). Ifchar
is signed, you have to be more careful. In this case, you probably want to assign the value mod 128 to yourchar
.In fact, since you are dealing with ASCII, you may want to do that anyway (ASCII is only up to 127).
Finally, obligatory portability remark: a
char
's value as an integer may not represent its ASCII value, if the underlying encoding is not ASCII—an example is EBCDIC.只需将其转换为
char
(如下所示)。如果要在字符串函数(strcat、strcmp 等)中使用它,则它必须位于末尾带有空终止符 ('\0'
) 的 char 数组中(也如下所示)....Just cast it to a
char
(as shown below). If you're going to use it in a string function (strcat, strcmp, etc), then it has to be in a char array with a null terminator ('\0'
) at the end (also shown below)....只需将其转换为字符即可:
Just cast it to a char:
char
只是一个具有255
值范围的整数,而像'a'
这样的字符文字也只是一个数字。只需转换为字符即可。
要使用像
strcmp
这样的东西,你需要一个char*
。该函数需要一个指向字符数组的第一个元素(以零结尾)的指针,而不是单个字符的地址。所以你想要:
A
char
is just an integer with a range of255
values, and character literals like'a'
are just a number as well.Just cast to a char.
To use something like
strcmp
you need achar*
though. The function expects a pointer to the first element of an array of chars (zero terminated) though and not the address of a single char.So you want:
在 C 中,
char
基本上是 0 到 255 之间的int
,因此如果您想 sprintf 到缓冲区或类似的缓冲区,可以将整数直接视为 char。事实上,您可能想让您的函数返回一个char
,以使发生的情况变得显而易见。In C, a
char
is basically anint
between 0 and 255, so you can treat the integer directly as a char if you want to sprintf to a buffer or similar. You might want to make your function return achar
, in fact, to make it obvious what's going on.