Reader Level:
ARTICLE

Convert Double to Byte Array in C#

On February 08, 2010 Articles | How do I
This code snippet shows how to convert double to a byte array.
  • 0
  • 0
  • 29947

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

    }

}


Mahesh Chand

Mahesh Chand is founder of C# Corner. C# Corner founded in 1999 is a FREE member contributions based open platform for developers to solve problems, learn new technology and hang out.  M...

  • 1rank
  • 71M readers
  • 9times
COMMENT USING

Trending up