Convert String to Byte Array in C#

C# Converting string to a byte array: Here, we will figure out how to change over an offered string to its proportionate byte[]?

String to Byte Array Conversion in C#

In C#, it is conceivable that a string can be changed over to a byte array by utilizing Encoding.ASCII.GetBytes() technique, it acknowledges a string as a parameter and returns a byte array.

Note: In C#, the string contains two bytes for every character; the strategy changes over it into 1 byte. In any case, some of the time it is conceivable to lose the information.

Syntax:

    byte[] Encoding.ASCII.GetBytes(String_Object);

Strategy Encoding.ASCII.GetBytes() contains different over-burden strategies, here we are utilizing the accompanying technique type…

Example:

This example contains a consistent string and changing over it to byte[]

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello World! I am JustTech@123.";
            
            //reading all characters as byte and storing them to byte[]
            byte[] barr = Encoding.ASCII.GetBytes(str);

            //printing characters with byte values
            for(int loop =0; loop<barr.Length-1; loop++)
            {
                Console.WriteLine("Byte of char \'" + str[loop] + "\' : " + barr[loop]);
            }

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output:

Byte of char 'H' : 72
Byte of char 'e' : 101
Byte of char 'l' : 108
Byte of char 'l' : 108
Byte of char 'o' : 111
Byte of char ' ' : 32
Byte of char 'W' : 87
Byte of char 'o' : 111
Byte of char 'r' : 114
Byte of char 'l' : 108
Byte of char 'd' : 100
Byte of char '!' : 33
Byte of char ' ' : 32
Byte of char 'I' : 73
Byte of char ' ' : 32
Byte of char 'a' : 97
Byte of char 'm' : 109
Byte of char ' ' : 32
Byte of char 'I' : 73
Byte of char 'n' : 110
Byte of char 'c' : 99
Byte of char 'l' : 108
Byte of char 'u' : 117
Byte of char 'd' : 100
Byte of char 'e' : 101
Byte of char 'H' : 72
Byte of char 'e' : 101
Byte of char 'l' : 108
Byte of char 'p' : 112
Byte of char '@' : 64
Byte of char '1' : 49
Byte of char '2' : 50
Byte of char '3' : 51

Leave a Comment

error: Alert: Content is protected!!