Tuesday, June 16, 2026

C# How To Convert String Into Byte Array

Technique 1. Let each character of string is of 1 byte. Convert each character into byte type and store that byte in byte array. We use length of string as target byte array size to loop through the target byte array and initialize its each element.

class StringToByteArray
{
    static void Main()
    {
        string surname = "Gupta";
        byte[] bytes = new byte[surname.Length];
        // Convert each character to its ASCII value and store it in the byte array
        for (int i = 0; i < surname.Length; i++)
        {
            bytes[i] = (byte)surname[i];
            // bytes[i] = Convert.ToByte(surname[i]);
        }

    }
}
Technique 2. One line solution by using Encoding class:
string surname = "Gupta";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(surname);

No comments:

Post a Comment

Hot Topics