How to Convert a Byte Array to Double in C#

This code snippet is an example of how to convert a byte array into a double number. Code also available to convert a double number into a byte array. 
 
The BitConverter class in .NET Framework provides functionality to convert base datatypes 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 converts that to an 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 in Listing 1 converts a double to a byte array and vice-versa. 
  1. class Program  
  2. {  
  3.    static void Main(string[] args)  
  4.    {  
  5.       Console.WriteLine("Double and byte arrays conversion sample.");  
  6.       // Create double to a byte array  
  7.       double d = 12.09;  
  8.       Console.WriteLine("Double value: " + d.ToString());  
  9.       byte[] bytes = ConvertDoubleToByteArray(d);  
  10.       Console.WriteLine("Byte array value:");  
  11.       Console.WriteLine(BitConverter.ToString(bytes));  
  12.       Console.WriteLine("Byte array back to double:");  
  13.   
  14.       // Create byte array to double  
  15.       double dValue = ConvertByteArrayToDouble(bytes);  
  16.       Console.WriteLine(dValue.ToString());  
  17.       Console.ReadLine();  
  18.    }  
  19.   
  20.    public static byte[] ConvertDoubleToByteArray(double d)  
  21.    {  
  22.       return BitConverter.GetBytes(d);  
  23.    }  
  24.    public static double ConvertByteArrayToDouble(byte[] b)  
  25.    {  
  26.       return BitConverter.ToDouble(b, 0);  
  27.    }  
  28. }  
Listing 1.
 
Figure 1 is the output of Listing 1.
 
Byte Array to Double in C# 
Figure 1. 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.