Mohanapriya R Mohanapriya R
Updated date Sep 22, 2024
In this article, we will explore the various methods for converting strings to bytes in C#.
  • 2.2k
  • 0
  • 0

Convert Strings to Bytes in C#

Strings in C# are sequences of characters, while bytes represent raw binary data. Converting a string to bytes involves encoding the characters in a specific format, such as UTF-8 or ASCII, to produce a byte array.

C# Program:

using System;
using System.Text;

class StringToBytesConverter
{
    static void Main()
    {
        // Input string
        string inputString = "Hello, TechieHook!";

        // Convert string to byte array using UTF-8 encoding
        byte[] byteArray = Encoding.UTF8.GetBytes(inputString);

        // Display the original string and the resulting byte array
        Console.WriteLine($"Original String: {inputString}");
        Console.WriteLine("Byte Array:");

        foreach (byte b in byteArray)
        {
            Console.Write($"{b:X2} "); // Display byte in hexadecimal format
        }
        Console.ReadKey();
    }
}

We have declared a string (inputString) that we want to convert to bytes. The Encoding.UTF8.GetBytes() method is used to convert the string to a byte array using UTF-8 encoding. Then we displayed the output string and byte array as shown below,

Output:

Original String: Hello, TechieHook!
Byte Array:
48 65 6C 6C 6F 2C 20 54 65 63 68 69 65 48 6F 6F 6B 21

Comments (0)

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