SIGN UP MEMBER LOGIN:    
ARTICLE

Convert Double to Byte Array in C#

Posted by Mahesh Chand Articles | How do I February 08, 2010
This code snippet shows how to convert double to a byte array.
Reader Level:

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);

    }

}


Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Nevron Gauge for SharePoint
Become a Sponsor