Find the ASCII or Unicode value of a character

From CodeCodex

Implementations[edit]

C[edit]

get the ASCII code

#include <stdio.h>

main ()
{
    char 
    A = "A",
    B = 'B',
    C = 'C',
    a = 'a',
    b = 'b',
    c = 'c',
    x = '>',
    y = '|',
    z = '#';

    printf ("%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n", A, B, C, a, b, c, x, y, z);
}

Output:

65
66
67
97
98
99
62
124
35

C++[edit]

The char type is already an integer type, so you can simply use it in most places that you would use an int. To print it out as an integer (since characters are usually printed out as the character and not the integer value), simply cast it into an int.

#include <iostream>
using namespace std;

int main() {
	cout << (int)'A' << endl;
	cout << (int)'B' << endl;
	cout << (int)'C' << endl;
	cout << (int)'a' << endl;
	cout << (int)'b' << endl;
	cout << (int)'c' << endl;
}

Output will be:

65
66
67
97
98
99

Erlang[edit]

$a.     % 97

Haskell[edit]

Char.ord 'a' -- 97

Java[edit]

Getting the ASCII or Unicode value of a character is simple in Java. The char type is already an integer type, so you can simply use it in most places that you would use an int. To print it out as an integer (since characters are usually printed out as the character and not the integer value), simply cast it into an int.

public static void main(String[] args) {
	System.out.println((int)'A');
	System.out.println((int)'B');
	System.out.println((int)'C');
	System.out.println((int)'a');
	System.out.println((int)'b');
	System.out.println((int)'c');
}

Output will be:

65
66
67
97
98
99

Note that this is actually the Unicode value of the character. However, the first 128 characters of Unicode are identical to ASCII, so it still works fine.

An example using unicode:

public static void main(String[] args) {
	System.out.println((int)'Θ');
	System.out.println((int)'AE'');
	System.out.println((int)'?');
}

Output will be:

920
508
8809

JavaScript[edit]

"a".charCodeAt(0); // 97

OCaml[edit]

int_of_char 'a' (* 97 *)

Perl[edit]

ord "a"; # 97

PHP[edit]

ord('a'); // 97, ASCII only.

Python[edit]

ord('a') # 97

Ruby[edit]

# ruby 1.8:
?a #97

# ruby 1.9:
"a".ord #97

Scheme[edit]

(char->integer #\a) ; 97

Seed7[edit]

Seed7 uses UTF-32 as internal representation for characters and strings. The integer value of a character is evaluated with ord(ch).

 $ include "seed7_05.s7i";

 const proc: main is func
   begin
     writeln(ord('A'));
     writeln(ord('B'));
     writeln(ord('C'));
     writeln(ord('a'));
     writeln(ord('b'));
     writeln(ord('c'));
     writeln(ord('µ'));
     writeln(ord('¼'));
     writeln(ord('€'));
   end func;

Zsh[edit]

for i in A B C a b c; print $((#i))

See Also[edit]