Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion double array to byte array

Tags:

c#

c#-3.0

How do I convert a double[] array to a byte[] array and vice versa?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(sizeof(double));
        Console.WriteLine(double.MaxValue);

        double[] array = new double[] { 10.0, 20.0, 30.0, 40.0 };
        byte[] convertedarray = ?

        Console.Read();
    }
}
like image 343
Raghaav Avatar asked Aug 05 '11 07:08

Raghaav


People also ask

How to convert double array to byte array in java?

Method. convert an array of double values to an array of byte . final byte[] res; int i; res = new byte[array. length]; i = 0; for (final double x : array) { res[i++] = ((byte) x); return res; ...

How to convert double to byte in java?

byteValue() is a built-in method in Java that returns the value of this Double as a byte(by casting to a byte).

How to convert double to byte in c#?

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.


1 Answers

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;
}
like image 138
Jeff Mercado Avatar answered Oct 07 '22 19:10

Jeff Mercado