
In this article, learn how to convert ASCII string to Hexadecimal string. ASCII (American Standard Code for Information Interchange) is a standard for encoding characters (letters, numbers, punctuation, and other symbols) into a series of numbers that can be understood by computers. Each ASCII character is represented by a unique number between 0 and 127.
Hexadecimal (or “hex” for short) is a numeral system that uses base 16, as opposed to the base 10 system used in decimal. Each hexadecimal digit represents four bits of data, making it a convenient way to represent binary-encoded data, like the ASCII characters.
The conversion of an ASCII string to a Hexadecimal string is the process of converting each character of the ASCII string to its corresponding hexadecimal representation. This is done by taking the ASCII value of each character, which is a number between 0 and 127, and converting it to its hexadecimal equivalent. The resulting string is a series of hexadecimal values separated by spaces, representing the original ASCII characters.
This conversion is widely used in computing, particularly in networking and data transmission, where data needs to be encoded in a way that can be transmitted reliably across a network. The hexadecimal representation of the data is more compact and easier to transmit than the ASCII representation, but it can be converted back to the original ASCII representation when needed.
Convert ASCII string to Hexadecimal string in .Net C#
This example shows how to convert ASCII string to Hexadecimal string.
using System; using System.IO; class program { public static void Main() { string sHexOutput= ""; string sASCIIString = "30303132"; if (!string.IsNullOrEmpty(sASCIIString)) { for (int i = 0; i < sASCIIString .Length / 2; i++) { string hexChar = sASCIIString .Substring(i * 2, 2); int hexValue = Convert.ToInt32(hexChar, 16); sHexOutput+= Char.ConvertFromUtf32(hexValue); } } } }
Here is an another example of a .NET program that converts an ASCII string to a Hexadecimal string:
using System; using System.Linq; class Program { static void Main(string[] args) { string input = "Hello World!"; string output = StringToHex(input); Console.WriteLine("Hexadecimal representation of '{0}': {1}", input, output); Console.ReadLine(); } static string StringToHex(string input) { return String.Concat(input.Select(c => ((int)c).ToString("X2"))); } }
In this example, the StringToHex method takes an ASCII string as an input and it converts each character to its corresponding hexadecimal representation using the ToString("X2") method. It then concatenates all the hexadecimal values using the String.Concat() method, returning the result as a string.
This program will output:
Hexadecimal representation of 'Hello World!': 48656C6C6F20576F726C6421
- Article ends here -