Convert Double 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 or other base type value and convert that to a array of bytes. The BitConverter class also have other static methods to reverse this conversion. Some of these methods are ToDouble, ToChart, ToBoolean, ToInt16, and ToSingle.

The following code snippet converts a double to a byte array and vice-versa.

class Program

{

    static void Main(string[] args)

    {

        Console.WriteLine("Double and byte arrays conversion sample.");

        // Create double to a byte array

        double d = 12.09;

        Console.WriteLine("Double value: " + d.ToString());

        byte[] bytes = ConvertDoubleToByteArray(d);

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

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

 

        Console.WriteLine("Byte array back to double:");

        // Create byte array to double

        double dValue = ConvertByteArrayToDouble(bytes);

        Console.WriteLine(dValue.ToString());

 

        Console.ReadLine();

    }

 

    public static byte[] ConvertDoubleToByteArray(double d)

    {

        return BitConverter.GetBytes(d);

    }

    public static double ConvertByteArrayToDouble(byte[] b)

    {

        return BitConverter.ToDouble(b, 0);

    }

}


Up Next
    Ebook Download
    View all
    Learn
    View all