Random int 1-255 to character in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jmoschetti45
    New Member
    • Feb 2010
    • 1

    Random int 1-255 to character in C

    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.
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    I don't understand what you want to do.

    Suppose the int value is 65 (0x41, the ASCII code for 'A'). What do you want in the string?
    • "65"
    • "41"
    • "0x41"
    • "A"

    If you want the last option ("A"), then what do you want to do if the integer value does not correspond to an printable ASCII character.

    No doubt you are only interested in ASCII character encoding.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      There is no need for a Chr() function in C/C++ because C/C++ does not deal with characters. It has a char type but this is just an integer in the range -128 - 127 (signed) or 0 - 255 (unsigned).

      You can all one of functions from ctype.h, isprint for example to determine if your integer value corresponds to a printable character. It it does just store it in variable of type char.

      Code:
      #include "stdio.h"
      #include "ctype.h"
      
      int main()
      {
          int value = <somevalue>;
      
          if (isprint(value)
          {
              char chav = value;
      
              printf("The value %d represents the printable character %c\n", value, chav);
          }
      }

      Comment

      Working...