c# - 如何在 C# 中将字节数组转换为 double 组?

标签 c# .net bytearray

我有一个包含 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/

相关文章:

C# Byte[] 字节数组到 Unicode 字符串

c# - 如何在 C# 中通过 DropBoxRest API 获取 Dropbox 文件?

c# - 将字体高度设置为文本 block 高度的一半

c# - 隔离存储

c# - 客户端收到时从服务器返回的字节数组不同

iphone - 字节数组到 NSData

c# - Entity Framework : Why DbSet<T> Loads all data

c# - 在 WPF 中添加动态按钮

c# - 使用搜索字符串提取段落

.net - 如何使用自定义结构代替 KeyValuePair?