The Wayback Machine - https://web.archive.org/web/20240828153531/https://www.geeksforgeeks.org/converting-a-string-to-its-equivalent-byte-array-in-c-sharp/
Open In App

Converting a String to its Equivalent Byte Array in C#

Last Updated : 28 May, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string, the task is to convert this string into a Byte array in C#.

Examples:

Input: aA
Output: [97, 65 ]
  
Input: Hello
Output: [ 72, 101, 108, 108, 111 ]

Method 1: 

Using ToByte() Method: This method is a Convert class method. It is used to converts other base data types to a byte data type.

Syntax:

byte byt = Convert.ToByte(char); 

Step 1: Get the string.

Step 2: Create a byte array of the same length as of string.

Step 3: Traverse over the string to convert each character into byte using the ToByte() Method and store all the bytes to the byte array.

Step 4: Return or perform the operation on the byte array.

Below is the implementation of the above approach:

C#




// C# program to convert a given
// string to its equivalent byte[]
    
using System;
  
public class GFG{
    
    static public void Main ()
    { 
        string str = "GeeksForGeeks"; 
    
        // Creating byte array of string length 
        byte[] byt = new byte[str.Length]; 
    
        // converting each character into byte 
        // and store it
        for (int i = 0; i < str.Length; i++) { 
            byt[i] = Convert.ToByte(str[i]); 
        } 
    
        // printing characters with byte values
        for(int i =0; i<byt.Length; i++)
        {
            Console.WriteLine("Byte of char \'" + str[i] + "\' : " + byt[i]);
        }
  
    } 
}


Output:

Byte of char 'G' : 71
Byte of char 'e' : 101
Byte of char 'e' : 101
Byte of char 'k' : 107
Byte of char 's' : 115
Byte of char 'F' : 70
Byte of char 'o' : 111
Byte of char 'r' : 114
Byte of char 'G' : 71
Byte of char 'e' : 101
Byte of char 'e' : 101
Byte of char 'k' : 107
Byte of char 's' : 115

Method 2: 

Using GetBytes() Method: The Encoding.ASCII.GetBytes() method is used to accepts a string as a parameter and get the byte array.

Syntax:

byte[] byte_array = Encoding.ASCII.GetBytes(string str); 

Step 1: Get the string.

Step 2: Create an empty byte array.

Step 3: Convert the string into byte[] using the GetBytes() Method and store all the convert string to the byte array.

Step 4: Return or perform the operation on the byte array.

C#




// C# program to convert a given
// string to its equivalent byte[]
    
using System;
using System.Text;
  
public class GFG{
    
    static public void Main ()
    { 
        string str = "GeeksForGeeks"; 
    
        // Creating byte array of string length 
        byte[] byt; 
    
        // converting each character into byte 
        // and store it
        byt = Encoding.ASCII.GetBytes(str);
    
        // printing characters with byte values
        for(int i =0; i<byt.Length; i++)
        {
            Console.WriteLine("Byte of char \'" + str[i] + "\' : " + byt[i]);
        }
  
    } 
}


Output:

Byte of char 'G' : 71
Byte of char 'e' : 101
Byte of char 'e' : 101
Byte of char 'k' : 107
Byte of char 's' : 115
Byte of char 'F' : 70
Byte of char 'o' : 111
Byte of char 'r' : 114
Byte of char 'G' : 71
Byte of char 'e' : 101
Byte of char 'e' : 101
Byte of char 'k' : 107
Byte of char 's' : 115


Similar Reads

C# | Byte.CompareTo(Byte) Method
This method is used to compare this instance to a specified 8-bit unsigned integer and returns an indication of their relative values.Syntax: public int CompareTo (byte value); Here, the value is an 8-bit unsigned integer to compare.Return Value: This method returns a signed integer that indicates the relative order of this instance and value. Less
2 min read
C# | Byte.Equals(Byte) Method
This method is used to return a value indicating whether this instance and a specified Byte object represent the same value. Syntax: public bool Equals (byte obj); Here, obj is a byte object to compare to this instance. Return Value: This method returns true if obj is equal to this instance otherwise, it returns false. Below programs illustrate the
2 min read
C# | Converting an array of one type to an array of another type
Array.ConvertAll(TInput[], Converter&lt;TInput, TOutput&gt;) Method is used to convert an array of one type to an array of another type. Syntax: public static TOutput[] ConvertAll&lt;TInput,TOutput&gt; (TInput[] array, Converter&lt;TInput,TOutput&gt; converter); Here, TInput and TOutput is the source array and target array respectively. Parameters:
3 min read
Converting Enumerated type to String according to the Specified Format in C#
Enum.Format(Type, Object, String) Method is used to convert the specified value of a specified enumerated type to its equivalent string representation according to the specified format. Syntax: public static string Format (Type enumType, object value, string format); Parameters: enumType: It is the enumeration type of the value to convert. value: I
2 min read
Program to convert Byte array to IP Address
Given a Byte Array, convert it to the format of IP Address. Examples: Input : {16, 16, 16, 16} Output : 16.16.16.16Input : {172, 31, 102, 14} Output : 172.31.102.14Byte arrays: A byte is a collection of bits (8). Byte arrays are arrays of contiguous bytes and can be used to store binary information. With byte arrays, one can work directly on bytes
3 min read
C# Program to Find Binary Equivalent of an Integer using Recursion
Given an integer number, now we convert the given integer number into a binary number using recursion. Recursion is a method in which a function calls itself directly or indirectly and such type of function is known as a recursive function. It solves the problem very efficiently like we find the binary equivalent of an integer. Examples: Input : 10
3 min read
C# | BitConverter.ToString(Byte[]) Method
This method is used to convert the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation. Syntax: public static string ToString (byte[] value); Here, the value is an array of bytes. Return Value: This method returns a string of hexadecimal pairs separated by hyphens, where each pair represen
2 min read
C# | Byte.GetHashCode() Method
This method is used to return the hash code for the given byte.Syntax: public override int GetHashCode (); Return Value: This method returns a hash code for the current Byte.Below programs illustrate the use of Byte.GetHashCode() Method:Example 1: C/C++ Code // C# program to demonstrate // Byte.GetHashCode Method using System; class GFG { // Main M
2 min read
C# | Byte.GetTypeCode() Method
This method is used to return the TypeCode for value type Byte. Syntax: public TypeCode GetTypeCode (); Return Value: It returns the enumerated constant, Byte.Below programs illustrate the use of Byte.GetTypeCode() Method:Example 1: C/C++ Code // C# program to demonstrate // Byte.GetTypeCode() Method using System; class GFG { // Main Method public
2 min read
C# | Byte.ToString Method | Set - 1
This method is used to convert the value of the current Byte object to its equivalent string representation. There are total 4 methods in the overload list of Byte.ToString() Method as follows: ToString(IFormatProvider) ToString(String, IFormatProvider) ToString() ToString(String) ToString(IFormatProvider) This method is used to Converts the numeri
4 min read
Byte Struct in C#
In C#, Byte Struct is used to represent 8-bit unsigned integers. The Byte is an immutable value type and the range of Byte is from 0 to 255. This class allows you to create Byte data types and you can perform mathematical and bitwise operations on them like addition, subtraction, multiplication, division, XOR, AND etc. .math-table { border-collapse
3 min read
C# | Byte.CompareTo(Object) Method
This method is used to compare the current instance to a specified object and returns a sign of their relative values. Regardless of value, any instance of Byte will be considered greater than null. Syntax: public int CompareTo (object value); Here, it takes an object to compare, or null. Return Value: It returns a signed integer indicating the rel
2 min read
C# | Byte.Equals(Object) Method
This method is used to get a value which indicates whether the current instance is equal to a specified object or not. Syntax: public override bool Equals (object obj); Here, it takes an object to compare with the current instance or null. Return Value: This method returns true if obj is an instance of Byte and equals the value of current instance
2 min read
C# | Byte.MinValue Field
The MinValue field of Byte Struct is used to represent the minimum possible value of byte data type. The value of this field is constant means that a user cannot change the value of this field. The value of this field is 0. Syntax: public const byte MinValue = 0; Return Value: This field always returns 0. Example: // C# program to illustrate the //
1 min read
C# | Byte.MaxValue Field
The MaxValue field of Byte Struct is used to represent the maximum value of the byte data type. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 255. Its hexadecimal value is 0xFF. Syntax: public const byte MaxValue = 255; Return Value: This field always returns 255. Example:
1 min read
Difference between byte and sbyte in C#
In C#, a single byte is used to store 8-bits value. The byte and sbyte both are used for byte type of data. byte : This Struct is used to represent 8-bit unsigned integers. The byte is an immutable value type and the range of Byte is from 0 to 255. Example : C/C++ Code // C# program to demonstrate // the byte Struct Fields using System; using Syste
2 min read
byte Keyword in C#
Keywords are the words in a language that are used for some internal process or represent some predefined actions. byte is a keyword that is used to declare a variable which can store an unsigned value range from 0 to 255. It is an alias of System.Byte. byte keyword occupies 1 byte (8 bits) in the memory. Syntax: byte variable_name = value; Example
2 min read
File.Replace(String, String, String) Method in C# with Examples
File.Replace(String, String, String) is an inbuilt File class method that is used to replace the contents of a specified destination file with the contents of a source file then it deletes the source file and creates a backup of the replaced file.Syntax: public static void Replace (string sourceFileName, string destinationFileName, string destinati
3 min read
File.Replace(String, String, String, Boolean) Method in C# with Examples
File.Replace(String, String, String, Boolean) is an inbuilt File class method that is used to replace the contents of a specified destination file with the contents of a source file then it deletes the source file, creates a backup of the replaced file, and optionally ignores merge errors. Syntax: public static void Replace (string sourceFileName,
3 min read
C# | Equals(String, String) Method
In C#, Equals(String, String) is a String method. It is used to determine whether two String objects have the same value or not. Basically, it checks for equality. If both strings have the same value, it returns true otherwise returns false. This method is different from Compare and CompareTo methods. This method compares two string on the basis of
2 min read
C# | How to copy a String into another String
String.Copy(String) Method is used to create a new instance of String with the same value as a specified String. In other words, this method is used to copy the data of one string into a new string. The new string contains same data like an original string but represents a different object reference. Syntax: public static string Copy (string value)
2 min read
File.Copy(String, String) Method in C# with Examples
File.Copy(String, String) is an inbuilt File class method that is used to copy the content of the existing source file content to another destination file which is created by this function. Syntax: public static void Copy (string sourceFileName, string destFileName); Parameter: This function accepts two parameters which are illustrated below: sourc
3 min read
File.AppendAllText(String, String) Method in C# with Examples
File.AppendAllText(String, String) is an inbuilt File class method which is used to append the specified string to the given file if that file exists else creates a new file and then appending is done. It also closes the file.Syntax: public static void AppendAllText (string path, string contents); Parameter: This function accepts two parameters whi
3 min read
File.AppendAllText(String, String, Encoding) Method in C# with Examples
File.AppendAllText(String, String, Encoding) is an inbuilt File class method which is used to append the specified string to the given file using the specified encoding if that file exists else creates a new file and then appending is done. Syntax: public static void AppendAllText (string path, string contents, System.Text.Encoding encoding); Param
3 min read
File.WriteAllText(String, String) Method in C# with Examples
File.WriteAllText(String, String) is an inbuilt File class method that is used to create a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten. Syntax: public static void WriteAllText (string path, string contents); Parameter: This function accepts two parameters which ar
3 min read
File.WriteAllText(String, String, Encoding) Method in C# with Examples
File.WriteAllText(String, String, Encoding) is an inbuilt File class method that is used to create a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. Syntax: public static void WriteAllText (string path, string contents, System.Text.Encodi
3 min read
File.WriteAllLines(String, String[], Encoding) Method in C# with Examples
File.WriteAllLines(String, String[], Encoding) is an inbuilt File class method that is used to create a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.Syntax: public static void WriteAllLines (string path, string[] contents, System.Text.Encoding encoding); Parameter: This function a
3 min read
File.WriteAllLines(String, String[]) Method in C# with Examples
File.WriteAllLines(String, String[]) is an inbuilt File class method that is used to create a new file, writes the specified string array to the file, and then closes the file.Syntax: public static void WriteAllLines (string path, string[] contents); Parameter: This function accepts two parameters which are illustrated below: path: This is the spec
3 min read
File.WriteAllLines(String, IEnumerable&lt;String&gt;, Encoding) Method in C# with Examples
File.WriteAllLines(String, IEnumerable&lt;String&gt;, Encoding) is an inbuilt File class method that is used to create a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. Syntax: public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable&lt;String&gt; contents,
3 min read
File.WriteAllLines(String, IEnumerable&lt;String&gt;) Method in C# with Examples
File.WriteAllLines(String, IEnumerable&lt;String&gt;) is an inbuilt File class method that is used to create a new file, writes a collection of strings to the file, and then closes the file. Syntax: public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable&lt;String&gt;contents); Parameter: This function accepts two para
3 min read