Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a byte array to double array in C#?

Tags:

c#

.net

bytearray

I have a byte array which contains double values. I want to convert It to double array. Is it possible in C#?

Byte array looks like:

byte[] bytes; //I receive It from socket

double[] doubles;//I want to extract values to here

I created a byte-array in this way (C++):

double *d; //Array of doubles
byte * b = (byte *) d; //Array of bytes which i send over socket
like image 401
Vasya Avatar asked Oct 20 '11 06:10

Vasya


People also ask

How do you convert Bytearray?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Can we convert byte to double in Java?

Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.

Can we convert byte array to file in Java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.


2 Answers

You can't convert an array type; however:

byte[] bytes = ...
double[] values = new double[bytes.Length / 8];
for(int i = 0 ; i < values.Length ; i++)
    values[i] = BitConverter.ToDouble(bytes, i * 8);

or (alterntive):

byte[] bytes = ...
double[] values = new double[bytes.Length / 8];
Buffer.BlockCopy(bytes, 0, values, 0, values.Length * 8);

should do. You could also do it in unsafe code:

byte[] bytes = ...
double[] values = new double[bytes.Length / 8];
unsafe
{
    fixed(byte* tmp = bytes)
    fixed(double* dest = values)
    {
        double* source = (double*) tmp;
        for (int i = 0; i < values.Length; i++)
            dest[i] = source[i];
    }
}

not sure I recommend that, though

like image 106
Marc Gravell Avatar answered Oct 21 '22 14:10

Marc Gravell


I'll add a reference to the super-unsafe code from here C# unsafe value type array to byte array conversions

Be aware that it's based on an undocumented "feature" of C#, so tomorrow it could die.

[StructLayout(LayoutKind.Explicit)]
struct UnionArray
{
    [FieldOffset(0)]
    public byte[] Bytes;

    [FieldOffset(0)]
    public double[] Doubles;
}

static void Main(string[] args)
{
    // From bytes to floats - works
    byte[] bytes = { 0, 1, 2, 4, 8, 16, 32, 64 };
    UnionArray arry = new UnionArray { Bytes = bytes };

    for (int i = 0; i < arry.Bytes.Length / 8; i++)
        Console.WriteLine(arry.Doubles[i]);   
}

The only advantage of this method is that it doesn't really "copy" the array, so it's O(1) in space and time over other methods that copy the array that are O(n).

like image 28
xanatos Avatar answered Oct 21 '22 14:10

xanatos