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.
A char
in C can only take values from CHAR_MIN
to CHAR_MAX
. If char
is signed, CHAR_MAX
may be less than 255 (for example, a common value is 127). If char
is unsigned, CHAR_MAX
has to be at least 255.
Assuming your char
is unsigned, you can just assign the random number to a char
(in your string for example). If char
is signed, you have to be more careful. In this case, you probably want to assign the value mod 128 to your char
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With