PROWAREtech

articles » current » dot-net » convert-double-array-to-bytes

.NET: Convert Double Array to Byte Array

How to use the BitConverter class to convert an array of doubles to an array of bytes and back again; written in C#.

In C#, convert an array of doubles to an array of bytes and back again using the BitConverter class, which provides methods for converting base data types to an array of bytes and vice versa. Here’s how to do it:

1. Converting an Array of Doubles to an Array of Bytes

To convert an array of doubles to an array of bytes, iterate over the double array and convert each double to bytes. Since each double in C# is typically 8 bytes (64 bits), allocate an appropriate number of bytes to hold the converted values.


double[] doubleArray = new double[] { 1.0, 2.0, 3.0 };

byte[] byteArray = new byte[doubleArray.Length * sizeof(double)];

// NOTE: sizeof(double) is typically 8 (bytes)
for (int i = 0; i < doubleArray.Length; i++)
{
    BitConverter.GetBytes(doubleArray[i]).CopyTo(byteArray, i * sizeof(double));
}

2. Converting an Array of Bytes Back to an Array of Doubles

To convert the byte array back to a double array, read every 4 bytes from the byte array and convert them back into doubles.

 
double[] convertedDoubleArray = new double[byteArray.Length / sizeof(double)];

for (int i = 0; i < convertedDoubleArray.Length; i++)
{
    convertedDoubleArray[i] = BitConverter.ToDouble(byteArray, i * sizeof(double));
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE