我有一个包含 double 值的字节数组。我想将它转换为双数组。在 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# - 如何在 C# 中将字节数组转换为 double 组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7832120/