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.
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)....
int num = myrand(1,255);
char str[2] = {(char)num, '\0'};
...
if(strcmp(str, otherString...
Just cast it to a char:
char c = (char)myRandomInt;
A char
is just an integer with a range of 255
values, and character literals like 'a'
are just a number as well.
Just cast to a char.
char C = 67;
char c = 'c';
char zero = 'c' - 'c';
char also_zero = c - 'c';
/*Note: zero == 0*/
To use something like strcmp
you need a char*
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:
char szp[] = {c, '\0'};
int isDifferent = strcmp(szp, "c");
In C, a char
is basically an int
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 a char
, in fact, to make it obvious what's going on.
精彩评论