如何在C#中将字节数组转换为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#unsafe值类型数组添加对超不安全代码的引用到字节数组转换
请注意,它基于C#的无证“function”,所以明天它可能会死。
[StructLayout(LayoutKind.Explicit)] struct UnionArray { [FieldOffset(0)] public byte[] Bytes; [FieldOffset(0)] public double[] Doubles; } static void Main(string[] args) { // From bytes to floats - works byte[] bytes = { 0, 1, 2, 4, 8, 16, 32, 64 }; UnionArray arry = new UnionArray { Bytes = bytes }; for (int i = 0; i < arry.Bytes.Length / 8; i++) Console.WriteLine(arry.Doubles[i]); }
这种方法的唯一优点是它不会真正“复制”数组,因此在空间和时间上的O(1)是复制O(n)数组的其他方法。