将double数组转换为byte数组
如何将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(); } }
假设您希望将双精度数放在相应的字节数组中,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; }
您可以使用Select
和ToArray
方法将一个数组转换为另一个数组:
oneArray = anotherArray.Select(n => { // the conversion of one item from one type to another goes here }).ToArray();
要从double转换为byte:
byteArray = doubleArray.Select(n => { return Convert.ToByte(n); }).ToArray();
要从字节转换为双精度,只需更改转换部分:
doubleArray = byteArray.Select(n => { return Convert.ToDouble(n); }).ToArray();
如果要将每个double转换为多字节表示,可以使用SelectMany
方法和BitConverter
类。 由于每个double都会产生一个字节数组,因此SelectMany
方法会将它们展平为单个结果。
byteArray = doubleArray.SelectMany(n => { return BitConverter.GetBytes(n); }).ToArray();
要转换回双精度数,您需要一次循环八个字节:
doubleArray = Enumerable.Range(0, byteArray.Length / 8).Select(i => { return BitConverter.ToDouble(byteArray, i * 8); }).ToArray();
使用Bitconverter类。
double[] array = new double[] { 10.0, 20.0, 30.0, 40.0 }; byte[] convertedarray = array.Select(x => Convert.ToByte(x)).ToArray();
我想你可以使用这样的东西:
byte[] byteArray = new byteArray[...]; ... byteArray.SetValue(Convert.ToByte(d), index);
您应该使用Buffer.BlockCopy
方法。
看一下页面示例,你会清楚地了解。
doubleArray = byteArray.Select(n => {return Convert.ToDouble(n);}).ToArray();
var byteArray = (from d in doubleArray select (byte)d) .ToArray(); var doubleArray = (from b in byteArray select (double)b) .ToArray();
干杯。