tags:

views:

303

answers:

5

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.

+3  A: 

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");
Brian R. Bondy
`CHAR_MAX` has to be as most 127 if `char` is signed. Did you mean `zero = C - 'c';`? `'c' - 'c'` is obviously 0. But if you did mean `C - 'c';`, then that's not guaranteed by the standard (although in most cases it will be 0).
Alok
@Alok: Whether or not 67 == 'C' doesn't matter for the above answer. The important part was assigning an integer literal value. Fixed up wording about signed/unsigned. Thanks.
Brian R. Bondy
@Brian, yes. I was just commenting on your declaration and initialization of `char zero`.
Alok
@Alok: I did mean `'c' - 'c'`, but I added another one `c - 'c'`. I did not mean C - 'c' because the C is a capital C for 67 in ascii
Brian R. Bondy
+5  A: 

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...
SoapBox
+4  A: 

Just cast it to a char:

char c = (char)myRandomInt;
Anon.
+1  A: 

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.

dsolimano
+6  A: 
Alok
@serial_downvoter: I hope you have a good reason. :-)
Alok
Alok -- +1 just for that comment :P
Billy ONeal
@BillyONeal: Thanks. 3 of my answers got downvoted in a short amount of time - without any explanation. Sigh.
Alok