Home » C#.Net

Convert String to Byte Array in C#

C# | Converting string to byte array: Here, we are going to learn how to convert a given string to its equivalent byte[]?
Submitted by IncludeHelp, on February 09, 2019

Prerequisite: How to declare and use byte[] in C#?

String to Byte Array Conversion in C#

In C#, it is possible that a string can be converted to a byte array by using Encoding.ASCII.GetBytes() method, it accepts a string as a parameter and returns a byte array.

Note: In C#, the string contains two bytes per character; the method converts it into 1 byte. Still, sometimes it is possible to lose the data.

Syntax:

Method Encoding.ASCII.GetBytes() contains various overloaded methods, here we are using the following method type...

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

Example:

This example contains a constant string and converting it to byte[]

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello World! I am IncludeHelp@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
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.