[英]Deserialize a Byte Array created in C# in Python
I have a 2D jagged double array in C# which I converts to a byte array like this: 我在C#中有一个二维锯齿状双精度数组,我将其转换为字节数组,如下所示:
byte[][][] byteArray = new byte[10][][];
I am saving the byte array as a binary file in this way: 我以这种方式将字节数组保存为二进制文件:
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
formatter.Serialize(stream, byteArray);
}
Now, I need to read the file in python
in order to re-build there the 2D double array... 现在,我需要在
python
中读取文件,以便在那里重新构建2D双数组...
I was trying to use numpy.fromfile()
and would like to know how this should be done. 我试图使用
numpy.fromfile()
,想知道应该怎么做。
From what I can tell, BinaryFormatter
and numpy.fromfile()
are not made to cross platforms, let alone languages. 据我所知,
BinaryFormatter
和numpy.fromfile()
并不是跨平台的,更不用说语言了。 It will be easier to use a format that is more cross-platform, like JSON. 使用更具跨平台的格式(例如JSON)会更容易。 The portion of converting the
double
to a byte[]
might also have issues, eg because of endianness. 例如,由于字节顺序,将
double
转换为byte[]
可能也会出现问题。 If the performance and data requirements aren't really an issue, it'd be easier to not complicate things. 如果性能和数据要求不是真正的问题,那么不使事情复杂化会更容易。
This example uses Json.NET for the C#: 此示例将Json.NET用于C#:
double[][] myArray = // whatever
var path = // whatever
using (StreamWriter file = File.CreateText(path))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, myArray);
}
And then in the Python all you have to do is something like: 然后在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.