Thread: how to get ASCIIi value of a char in a string

  1. #1
    Registered User
    Join Date
    Feb 2013

    how to get ASCIIi value of a char in a string


    how can I find ASCII value (0..255) of a character char in a string?

    I have an array of char:

    char myarray[50];
    and I need to have ASCII value of character eg myarray[10]. How can I do that?

    Thank you.

    (I am really a beginner..)

  2. #2
    Registered User
    Join Date
    Jun 2005
    The ASCII character set only defines 128 characters (0 to 127). The notion of an ASCII value greater than 127 is therefore meaningless. (Although the ASCII character set is a subset of several other modern character sets with 256 or more characters).

    Beyond that, it depends on what you are allowed to assume about your compiler and host system.

    If you are permitted to assume your compiler (and/or host system) uses the ASCII character (or a character set that is a superset of the ASCII character set) the solution is trivial.
        ascii_value_of_achar = (achar >= 0 && achar <= 127) ? ((int)achar) : (invalid_value);
    where invalid_value is a value of type int that is outside the range [0, 127]. Note this approach may trigger compiler warnings if your compiler supports 8-bit characters (an unsigned 8-bit char type is always non-negative, and a signed 8-bit char type always has value less than or equal to 127). I'll leave eliminating such warnings, while ensuring the code still works regardless of whether char is signed or unsigned, as an exercise. Simply loop over each character in a string.

    If your compiler/host supports another character set (eg a EBCDIC variant) then you'll need to get your hands on a published translation table, and implement a lookup table of some form.
    Last edited by grumpy; 03-04-2013 at 04:03 AM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 12-02-2012, 05:25 AM
  2. Replies: 11
    Last Post: 06-16-2011, 11:59 AM
  3. Replies: 2
    Last Post: 09-12-2010, 09:15 AM
  4. Replies: 8
    Last Post: 12-08-2009, 02:47 AM
  5. Appending char to string (char array)
    By sniper83 in forum C Programming
    Replies: 14
    Last Post: 04-15-2008, 06:48 AM