How to get the ASCII value of a character in Scala

Overview

ASCII stands for American Standard Code for Information Interchange. It is concerned with how information and communications are shared, encoded, and decoded among computers.

Information here refers to textual data and other encodings, including UFT-8, UTF-16, etc.

We can get the ASCII value for any character in Scala with the toInt method.

Syntax

character.toInt
The syntax for getting the ASCII value of a character in Scala

Parameter

character: This is the character whose ASCII value we want to get.

Return value

The value returned is an integer value which is the ASCII value of the character.

Example

object Main extends App {
// create some character
var char1:Char='A'
var char2:Char='!'
var char3:Char='3'
var char4:Char='v'
// print the ASCII values
printf("Character %c in ASCII value is: %d \n", char1 ,char1.toInt)
printf("Character %c in ASCII value is: %d \n", char2 ,char2.toInt)
printf("Character %c in ASCII value is: %d \n", char3 ,char3.toInt)
printf("Character %c in ASCII value is: %d \n", char4 ,char4.toInt)
}

Explanation

  • Lines 4-7: We create some characters in Scala.
  • Lines 10-13: We use the toInt method and print the characters with their corresponding ASCII values to the console.

Free Resources