2011-08-05 165 views
11

如何將double[]陣列轉換爲byte[]陣列,反之亦然?轉換雙陣列到字節陣列

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(); 
    } 
} 
+0

你想要的值(即轉換。 '10.0' - > 10)還是底層機器表示的八個字節(例如序列化)? – Richard

+1

我們在這裏談論什麼樣的轉換?你想獲取相應的double並將其「轉換」爲一個整型來獲取字節值?或者你想獲得每個double值的字節表示?你需要_clarify_。 –

+0

的意圖是使用BinaryWriter.Write()函數。但是這隻接受字節。我想獲得每個double值的字節表示形式? – Raghaav

回答

15

假設你想放置相應的字節數組一個在雙打前一後,LINQ可以做短期工作出這一點:

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

或者,你可以使用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; 
} 

要轉換回:

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; 
} 
+1

在我的情況下,GetBytesAlt比GetBytes更快。謝謝! – RredCat

+0

BlockCopy版本非常棒。感謝那。 –

-1
var byteArray = (from d in doubleArray 
       select (byte)d) 
       .ToArray(); 

var doubleArray = (from b in byteArray 
        select (double)b) 
        .ToArray(); 

乾杯。

+0

這將從大雙打中刪除一些數據。 – VMAtm

+0

好吧,好吧。我認爲這個問題還不夠清楚。 –

+0

問題 - 是的,但它在評論中被清除。 – VMAtm

0

您可以使用這樣的事情,我想:

byte[] byteArray = new byteArray[...]; 
... 
byteArray.SetValue(Convert.ToByte(d), index); 
2
double[] array = new double[] { 10.0, 20.0, 30.0, 40.0 }; 
byte[] convertedarray = array.Select(x => Convert.ToByte(x)).ToArray(); 
+0

如何將byte []轉換回double []。 – Raghaav

0

您應該使用Buffer.BlockCopy方法。

看看這個頁面的例子,你會清楚地理解。

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

您可以使用SelectToArray方法來一個數組轉換爲另一種:

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

從double轉換爲字節:

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

從字節翻一番你轉換隻需更改轉換部分:

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

如果你想每個雙轉換爲多字節表示,則可以使用SelectMany方法和BitConverter類。由於每個double都會產生一個字節數組,所以SelectMany方法會將它們變成單個結果。

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

轉換回雙打,你需要循環字節八點時間:

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

絕對正確。 +1 –