簡體   English   中英

如何在C#中將字節數組轉換為double數組?

[英]How to convert a byte array to double array in C#?

我有一個包含雙精度值的字節數組。 我想將它轉換為雙數組。 在C#中有可能嗎?

字節數組看起來像:

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

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

我用這種方式創建了一個字節數組(C ++):

double *d; //Array of doubles
byte * b = (byte *) d; //Array of bytes which i send over socket

你不能轉換數組類型; 然而:

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

或(交替):

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

應該做。 您也可以在unsafe代碼中執行此操作:

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];
    }
}

不過我不推薦這樣做

我將從這里C#unsafe值類型數組添加對超不安全代碼的引用到字節數組轉換

請注意,它基於C#的未記錄的“功能”,所以明天它可能會死。

[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]);   
}

這種方法的唯一優點是它不會真正“復制”數組,因此在空間和時間上的O(1)是復制O(n)數組的其他方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM