In previous article, I mentioned Solving Error "JsonException: A possible object cycle was detected" .NET Core but in this article, I have mentioned how we can get ascii value of char in C# using console application examples.
ASCII, stands for American Standard Code for Information Interchange and is a code associated with each character on the keyboard.
Get ASCII by Typecasting
We usually get ASCII value of character or string by typecasting the character value and get it's ASCII value in C#, so here is a complete example of this.
Typecasting is used to convert a value from one data type to another.
So, here is the complete C# Code example to convert character to ascii value using Typecasting
using System;
namespace CharToAscii
{
internal class Program
{
static void Main(string[] args)
{
string str = "HELLO WORLD";
foreach (char c in str)
{
Console.WriteLine((int)c);
}
}
}
}
Output:
72
69
76
76
79
32
87
79
82
76
68
Convert Each Character of string to Byte Array
In this example, we will pass the complete string and then get the ASCII values of characters in a string by converting the string into an array of bytes with byte[]
and displaying each character's ascii value by looping throught it, here is the C# Code for it.
using System;
using System.Text;
namespace CharToAscii
{
internal class Program
{
static void Main(string[] args)
{
string str = "HELLO WORLD";
byte[] ASCIIvalues = Encoding.ASCII.GetBytes(str);
foreach (var value in ASCIIvalues)
{
Console.WriteLine(value);
}
}
}
}
Output:
72
69
76
76
79
32
87
79
82
76
68
That's it, hope it helps, any of the above 2 methods will work, but I find Encoding.ASCII.GetBytes(str)
, much accurate, since in Typecasting method, the resulting codes are Unicode numbers and could potentially contain non-ASCII codes.
You may also like to read:
Deserialize XML string to Object in C#
Convert EPOC (Unix) time stamp to Datetime and Vice-Versa in C#
String to Float in C# (Various ways)
Select vs SelectMany in C# With Example
Lambda expression in C# (With Examples)
Convert C# Class to JSON with Example
Converting String to Enum OR Enum to String in C#