Sai A Sai A
Updated date Apr 29, 2023
This blog explores three different methods to convert strings to hexadecimal in C# - using the Encoding class, the StringBuilder class, and LINQ. The program, output, and explanation of each method are provided, along with a conclusion that highlights the importance of this skill in various applications.

Introduction:

Hexadecimal (often shortened as "hex") is a number system with a base of 16. It is commonly used in computing to represent numbers, colors, and characters. In C#, we can convert a string to hexadecimal using several methods. In this blog, we will explore various methods to convert strings to hexadecimal in C#, along with their program, output, and explanation.

Method 1: Using the Encoding Class

The Encoding class in C# provides methods to convert between different character encodings. We can use the GetBytes method of this class to convert a string to a byte array, and then convert the byte array to hexadecimal using the BitConverter class.

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string str = "Hello, World!";
        byte[] bytes = Encoding.UTF8.GetBytes(str);
        string hex = BitConverter.ToString(bytes);
        hex = hex.Replace("-", "");
        Console.WriteLine(hex);
    }
}

Output:

48656C6C6F2C20576F726C6421

In the above code, we first declare a string variable named "str" and assign it the value "Hello, World!". We then use the Encoding.UTF8.GetBytes method to convert this string to a byte array named "bytes". The UTF-8 encoding is used here because it is the most commonly used encoding for text.

Next, we use the BitConverter.ToString method to convert the byte array to a hexadecimal string. This method returns a string in the format "XX-XX-XX-XX-XX-XX-XX-XX", where XX is the hexadecimal representation of each byte in the array.

Finally, we remove the "-" characters from the string using the Replace method, and print the resulting hexadecimal string to the console.

Method 2: Using the StringBuilder Class

The StringBuilder class in C# provides methods to manipulate strings efficiently. We can use the AppendFormat method of this class to convert each character in the string to its hexadecimal representation and append it to a StringBuilder object.

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string str = "Hello, World!";
        StringBuilder hexBuilder = new StringBuilder();
        foreach (char c in str)
        {
            hexBuilder.AppendFormat("{0:X2}", (int)c);
        }
        string hex = hexBuilder.ToString();
        Console.WriteLine(hex);
    }
}

Output:

48656C6C6F2C20576F726C6421

In the above code, we first declare a string variable named "str" and assign it the value "Hello, World!". We then declare a StringBuilder object named "hexBuilder".

Next, we use a foreach loop to iterate through each character in the string. For each character, we use the AppendFormat method of the StringBuilder object to convert it to its hexadecimal representation using the "{0:X2}" format specifier. This specifier ensures that each hexadecimal value is two digits long.

Finally, we convert the StringBuilder object to a string using the ToString method, and print the resulting hexadecimal string to the console.

Method 3: Using LINQ

LINQ (Language-Integrated Query) is a feature in C# that provides a consistent way to query data from different data sources. We can use the LINQ Select method to convert each character in the string to its hexadecimal representation and join the resulting strings using the string.Join method.

using System;
using System.Linq;

class Program {
  static void Main(string[] args) 
  {
    string str = "Hello, World!";
    string hex = string.Join("", str.Select(c => ((int) c).ToString("X2")));
    Console.WriteLine(hex);
  }
}

Output:

48656C6C6F2C20576F726C6421

In the above code, we first declare a string variable named "str" and assign it the value "Hello, World!".

Next, we use the LINQ Select method to convert each character in the string to its hexadecimal representation using the lambda expression "(c => ((int)c).ToString("X2"))". This expression converts each character to an integer using the (int) cast, and then converts the integer to a hexadecimal string using the "X2" format specifier.

Finally, we join the resulting strings using the string.Join method and print the resulting hexadecimal string to the console.

Conclusion:

In this blog, we explored three different methods to convert strings to hexadecimal in C#. The first method uses the Encoding class to convert the string to a byte array, and then uses the BitConverter class to convert the byte array to a hexadecimal string. The second method uses the StringBuilder class to efficiently convert each character in the string to its hexadecimal representation. The third method uses LINQ to convert each character in the string to its hexadecimal representation and join the resulting strings.

Comments (0)

There are no comments. Be the first to comment!!!