Conversion double array to byte array

You can use the Select and ToArray methods to convert one array to another:

oneArray = anotherArray.Select(n => {
  // the conversion of one item from one type to another goes here
}).ToArray();

To convert from double to byte:

byteArray = doubleArray.Select(n => {
  return Convert.ToByte(n);
}).ToArray();

To convert from byte to double you just change the conversion part:

doubleArray = byteArray.Select(n => {
  return Convert.ToDouble(n);
}).ToArray();

If you want to convert each double to a multi-byte representation, you can use the SelectMany method and the BitConverter class. As each double will result in an array of bytes, the SelectMany method will flatten them into a single result.

byteArray = doubleArray.SelectMany(n => {
  return BitConverter.GetBytes(n);
}).ToArray();

To convert back to doubles, you would need to loop the bytes eight at a time:

doubleArray = Enumerable.Range(0, byteArray.Length / 8).Select(i => {
  return BitConverter.ToDouble(byteArray, i * 8);
}).ToArray();

Assuming you want the doubles placed in the corresponding byte array one after the other, LINQ can make short work out of this:

static byte[] GetBytes(double[] values)
{
    return values.SelectMany(value => BitConverter.GetBytes(value)).ToArray();
}

Alternatively, you could use Buffer.BlockCopy():

static byte[] GetBytesAlt(double[] values)
{
    var result = new byte[values.Length * sizeof(double)];
    Buffer.BlockCopy(values, 0, result, 0, result.Length);
    return result;
}

To convert back:

static double[] GetDoubles(byte[] bytes)
{
    return Enumerable.Range(0, bytes.Length / sizeof(double))
        .Select(offset => BitConverter.ToDouble(bytes, offset * sizeof(double)))
        .ToArray();
}

static double[] GetDoublesAlt(byte[] bytes)
{
    var result = new double[bytes.Length / sizeof(double)];
    Buffer.BlockCopy(bytes, 0, result, 0, bytes.Length);
    return result;
}

Tags:

C#

C# 3.0