How do you use the ASCII function to return the ASCII code for a given character?
Posted by AliceWk
Last Updated: June 01, 2024
In various programming and scripting languages, the ASCII function (or similar functions) is used to obtain the numeric ASCII code of a given character. Here are examples of how to use the ASCII function in a few different languages:
Python
In Python, you use the built-in ord() function:
char = 'A'
ascii_code = ord(char)
print(ascii_code)  # Output: 65
JavaScript
In JavaScript, you can use the charCodeAt method on a string:
let char = 'A';
let asciiCode = char.charCodeAt(0);
console.log(asciiCode);  // Output: 65
PHP
In PHP, you can use the ord() function:
$char = 'A';
$asciiCode = ord($char);
echo $asciiCode;  // Output: 65
Java
In Java, you can simply cast a character to an integer:
char ch = 'A';
int asciiCode = (int) ch;
System.out.println(asciiCode);  // Output: 65
SQL (Example in SQL Server)
In SQL Server, you can use the ASCII function:
SELECT ASCII('A') AS ascii_code;  -- Output: 65
Visual Basic (VBA)
In VBA, you can also use the Asc function:
Dim char As String
char = "A"
Dim asciiCode As Integer
asciiCode = Asc(char)
Debug.Print asciiCode  ' Output: 65
These functions will help you retrieve the ASCII value for any character you provide as input. Just replace 'A' with the character of your choice to get its corresponding ASCII code.