簡體   English   中英

反序列化用Python在C#中創建的字節數組

[英]Deserialize a Byte Array created in C# in Python

我在C#中有一個二維鋸齒狀雙精度數組,我將其轉換為字節數組,如下所示:

byte[][][] byteArray = new byte[10][][];

我以這種方式將字節數組保存為二進制文件:

BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
   formatter.Serialize(stream, byteArray);
}

現在,我需要在python中讀取文件,以便在那里重新構建2D雙數組...

我試圖使用numpy.fromfile() ,想知道應該怎么做。

據我所知, BinaryFormatternumpy.fromfile()並不是跨平台的,更不用說語言了。 使用更具跨平台的格式(例如JSON)會更容易。 例如,由於字節順序,將double轉換為byte[]可能也會出現問題。 如果性能和數據要求不是真正的問題,那么不使事情復雜化會更容易。

此示例將Json.NET用於C#:

double[][] myArray = // whatever

var path = // whatever
using (StreamWriter file = File.CreateText(path))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(file, myArray);
}

然后在Python中,您要做的就是:

import numpy
import json
path = # whatever
with open(path) as f:
    myArray = numpy.array(json.load(f))
# we now have the array! e.g.
print(myArray.dtype) # float64
print(myArray[0][0]) # 0.79449418131

暫無
暫無

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

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