Conversion double array to byte array

后端 未结 7 1262
面向向阳花
面向向阳花 2020-12-01 16:35

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

class Program
{
    static void Main(string[] args)
    {
              


        
7条回答
  •  情话喂你
    2020-12-01 17:03

    You can use the Select and ToArray methods to convert one array to another:

    oneArray = anotherArray.Select(n => {
      // the conversion of one item from one type to another goes here
    }).ToArray();
    

    To convert from double to byte:

    byteArray = doubleArray.Select(n => {
      return Convert.ToByte(n);
    }).ToArray();
    

    To convert from byte to double you just change the conversion part:

    doubleArray = byteArray.Select(n => {
      return Convert.ToDouble(n);
    }).ToArray();
    

    If you want to convert each double to a multi-byte representation, you can use the SelectMany method and the BitConverter class. As each double will result in an array of bytes, the SelectMany method will flatten them into a single result.

    byteArray = doubleArray.SelectMany(n => {
      return BitConverter.GetBytes(n);
    }).ToArray();
    

    To convert back to doubles, you would need to loop the bytes eight at a time:

    doubleArray = Enumerable.Range(0, byteArray.Length / 8).Select(i => {
      return BitConverter.ToDouble(byteArray, i * 8);
    }).ToArray();
    

提交回复
热议问题