Convert Char to Byte Array in C#


Convert Char to Byte Array in C#

 

The BitConverter class in .NET Framework is provides functionality to convert base data types to an array of bytes, and an array of bytes to base data types.

The BitConverter class has a static overloaded GetBytes method that takes an integer, double, bool, short, long, or other base type value and convert that to a array of bytes. The BitConverter class also has other static methods to reverse this conversion. Some of these methods are ToDouble, ToChart, ToBoolean, ToInt16, and ToSingle.

The following code snippet converts different float, long, short, char, and boolean values to a byte array and vice-versa.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace BitConverterSample

{

    class Program

    {

        static void Main(string[] args)

        {

 

            char charValue = 'c';

            Console.WriteLine("Char value: " + charValue.ToString());

            bytes = BitConverter.GetBytes(charValue);

            Console.WriteLine("Byte array value:");

            Console.WriteLine(BitConverter.ToString(bytes));

            // Create byte array to Char

            char charValueBack = BitConverter.ToChar(bytes, 0);

            Console.WriteLine(charValueBack.ToString());

            Console.WriteLine("--------------------------");

 

 

            Console.ReadLine();       

    }

}

 

 

Up Next
    Ebook Download
    View all
    Learn
    View all