ASCII (American Standard Code for Information Interchange) assigns a numerical value to each character. In programming, we often need to get the ASCII value of a character.
Examples:
Input: a
Output: 97Input: D
Output: 68
Explanation: The ASCII values of 'a' and 'D' are 97 and 68 respectively.
Below are few methods in different programming languages to print ASCII value of a given character :
In Python
Python provides the built-in ord() function to get the ASCII value of a character.
c = 'g'
print(ord(c))
Output
103
In C
In C, the %d format specifier can be used to print the ASCII value of a character:
#include <stdio.h>
int main() {
char c = 'k';
printf("%d",c);
return 0;
}
Output
107
In C++
In C++, we can use the int() function to convert a character to its ASCII value:
#include <iostream>
using namespace std;
int main() {
char c = 'A';
cout <<int(c);
return 0;
}
Output
65
In Java
In Java, assigning a char to an int variable gives its ASCII value:
public class AsciiValue {
public static void main(String[] args) {
char c = 'e';
int ascii = c;
System.out.println(ascii);
}
}
Output
101
In C#
The concept to print ascii in c# is similar to that of Java:
using System;
public class AsciiValue {
public static void Main() {
char c = 'e';
int ascii = c;
Console.WriteLine(ascii);
}
}
Output
101
In JavaScript
JavaScript provides the charCodeAt() method to get ASCII value:
val = 'A'
console.log(val.charCodeAt(0));
Output
65