how to get ASCIIi value of a char in a string

This is a discussion on how to get ASCIIi value of a char in a string within the C Programming forums, part of the General Programming Boards category; Hi, how can I find ASCII value (0..255) of a character char in a string? I have an array of ...

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    5

    how to get ASCIIi value of a char in a string

    Hi,

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

    I have an array of char:

    Code:
    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
    Posts
    6,245
    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.
    Code:
        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 03:03 AM.
    Right 98% of the time, and don't care about the other 3%.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 12-02-2012, 04: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, 01: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21