Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random int 1-255 to character in C

Tags:

c

random

char

int

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.

like image 832
jmoschetti45 Avatar asked Feb 25 '10 02:02

jmoschetti45


1 Answers

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.

like image 82
Alok Singhal Avatar answered Oct 22 '22 00:10

Alok Singhal