Get ASCII Value of Character in C#
-
Get ASCII Value of Characters in a String With Typecasting in
C#
-
Get ASCII Value of Characters in a String With
byte[]
inC#
This tutorial will discuss methods to ASCII value of characters in a string in C#.
Get ASCII Value of Characters in a String With Typecasting in C#
Typecasting is used to convert a value from one data type to another. ASCII, also known as American Standard Code for Information Interchange, is a code associated with each character on the keyboard. We can get the ASCII values of characters in a string by extracting each character from the string and typecasting it into Int
. The following code example shows us how we can get the ASCII value of characters in a string with typecasting in C#.
using System;
using System.Text;
namespace ASCII_value_of_a_string
{
class Program
{
static void Main(string[] args)
{
string str = "ABCDEFGHI";
foreach(var c in str)
{
Console.WriteLine((int)c);
}
}
}
}
Output:
65
66
67
68
69
70
71
72
73
We displayed the ASCII values of characters in a string with typecasting in C#. We initialized the string str
and used the foreach
loop to extract each character c
from str
. We used typecasting to convert each extracted character c
into Int
.
Get ASCII Value of Characters in a String With byte[]
in C#
If we don’t want to typecast each string’s character into an Int
, we can also use a byte array instead. We can get the ASCII values of characters in a string by converting the string into an array of bytes with byte[]
and displaying each element of the array. The following code example shows us how we can get the ASCII values of characters in a string with byte[]
in C#.
using System;
using System.Text;
namespace ASCII_value_of_a_string
{
class Program
{
static void Main(string[] args)
{
string str = "ABCDEFGHI";
byte[] ASCIIvalues = Encoding.ASCII.GetBytes(str);
foreach(var value in ASCIIvalues)
{
Console.WriteLine(value);
}
}
}
}
Output:
65
66
67
68
69
70
71
72
73
We displayed the ASCII values of characters in a string with byte[]
in C#. We initialized the string str
and used the Encoding.ASCII.GetBytes(str)
function to convert it into the array of bytes ASCIIvalues
. We used a foreach
loop to output each element in ASCIIvalues
.