我有一个字节数组,它包含双重价值。我想将其转换为双阵列。是否有可能在C#?
字节数组是这样的:
字节[]字节; //我收到它从插座
双[]双打; //我想提取值在这里
予以这种方式(C ++)创建了一个字节数组:
双* D; //双精度数组
字节* B =(BYTE *)D; //我送过来插座的字节数组
解决方案
您不能的转换的一个数组类型;但是:
字节[]字节= ...
双[]值=新的双[bytes.Length / 8]。
的for(int i = 0; I< values.Length;我++)
值[I] = BitConverter.ToDouble(字节,I * 8);
或(alterntive):
字节[]字节= ...
双[]值=新的双[bytes.Length / 8]。
Buffer.BlockCopy(字节数,0值,0,values.Length * 8);
应该做的。你也可以做到这一点在不安全
code:
字节[]字节= ...
双[]值=新的双[bytes.Length / 8]。
不安全
{
固定(BYTE * TMP =字节)
固定(双* DEST =值)
{
双*源=(双*)tmp目录;
的for(int i = 0; I< values.Length;我++)
DEST [i] =源[I]
}
}
不知道我建议,尽管
I have a byte array which contains double values. I want to convert It to double array. Is it possible in C#?
Byte array looks like:
byte[] bytes; //I receive It from socket
double[] doubles;//I want to extract values to here
I created a byte-array in this way (C++):
double *d; //Array of doubles
byte * b = (byte *) d; //Array of bytes which i send over socket
解决方案
You can't convert an array type; however:
byte[] bytes = ...
double[] values = new double[bytes.Length / 8];
for(int i = 0 ; i < values.Length ; i++)
values[i] = BitConverter.ToDouble(bytes, i * 8);
or (alterntive):
byte[] bytes = ...
double[] values = new double[bytes.Length / 8];
Buffer.BlockCopy(bytes, 0, values, 0, values.Length * 8);
should do. You could also do it in unsafe
code:
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];
}
}
not sure I recommend that, though