转换双阵列字节数组 [英] Conversion double array to byte array

查看:126
本文介绍了转换双阵列字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何转换双[] 阵列到字节[] 阵列,反之亦然?

 类节目
{
静态无效的主要(字串[] args)
{
Console.WriteLine(的sizeof(双));
Console.WriteLine(double.MaxValue);

双[]数组=新的双[] {10.0,20.0,30.0,40.0};
字节[] = convertedarray?

Console.Read();
}
}


解决方案

假设你想放置在相应的字节数组之一后,其他双打,LINQ能很快制定出这样的:

 静态字节[] GetBytes会(双[]值)
{
返回values​​.SelectMany。(价值=> BitConverter.GetBytes(值))ToArray的();
}



另外,你可以使用 Buffer.BlockCopy()

 静态的byte [] GetBytesAlt(双[]值)
{
VAR的结果=新的字节[values​​.Length *的sizeof(双)];
Buffer.BlockCopy(值0,结果0,result.Length);
返回结果;
}

要转换回:

 静态双重[] GetDoubles(字节[]字节)
{
返回Enumerable.Range(0,bytes.Length /的sizeof(双))
。选择(偏移=> BitConverter.ToDouble(字节偏移*的sizeof(双)))
.ToArray();
}

静态双重[] GetDoublesAlt(字节[]字节)
{
VAR的结果=新的双[bytes.Length /的sizeof(双)];
Buffer.BlockCopy(字节,0,结果,0,bytes.Length);
返回结果;
}


How do I convert a double[] array to a byte[] array and vice versa?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(sizeof(double));
        Console.WriteLine(double.MaxValue);

        double[] array = new double[] { 10.0, 20.0, 30.0, 40.0 };
        byte[] convertedarray = ?

        Console.Read();
    }
}

解决方案

Assuming you want the doubles placed in the corresponding byte array one after the other, LINQ can make short work out of this:

static byte[] GetBytes(double[] values)
{
    return values.SelectMany(value => BitConverter.GetBytes(value)).ToArray();
}

Alternatively, you could use Buffer.BlockCopy():

static byte[] GetBytesAlt(double[] values)
{
    var result = new byte[values.Length * sizeof(double)];
    Buffer.BlockCopy(values, 0, result, 0, result.Length);
    return result;
}

To convert back:

static double[] GetDoubles(byte[] bytes)
{
    return Enumerable.Range(0, bytes.Length / sizeof(double))
        .Select(offset => BitConverter.ToDouble(bytes, offset * sizeof(double)))
        .ToArray();
}

static double[] GetDoublesAlt(byte[] bytes)
{
    var result = new double[bytes.Length / sizeof(double)];
    Buffer.BlockCopy(bytes, 0, result, 0, bytes.Length);
    return result;
}

这篇关于转换双阵列字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆