Find the ASCII or Unicode value of a character
From CodeCodex
Contents |
[edit] Implementations
[edit] C
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
[edit] C++
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
[edit] Erlang
$a. % 97
[edit] Haskell
Char.ord 'a' -- 97
[edit] Java
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)'D');
System.out.println((int)'E');
System.out.println((int)'F');
}
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
[edit] JavaScript
"a".charCodeAt(0); // 97
[edit] OCaml
int_of_char 'a' (* 97 *)
[edit] Perl
ord "a"; # 97
[edit] PHP
ord('a'); // 97, ASCII only.
[edit] Python
ord('a') # 97
[edit] Ruby
# ruby 1.8: ?a #97 # ruby 1.9: "a".ord #97
[edit] Scheme
(char->integer #\a) ; 97
[edit] Seed7
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;
[edit] Zsh
for i in A B C a b c; print $((#i))
[edit] See Also
- See ASCII Table for more ASCII codes.