如何将 double[]
数组转换为 byte[]
数组,反之亦然?
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();
}
}
最佳答案
假设您希望将 double 值一个接一个地放置在相应的字节数组中,LINQ 可以简化此操作:
static byte[] GetBytes(double[] values)
{
return values.SelectMany(value => BitConverter.GetBytes(value)).ToArray();
}
或者,您可以使用 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;
}
转换回来:
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;
}
关于c# - 将 double 组转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6952923/