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();
}
}
Method. convert an array of double values to an array of byte . final byte[] res; int i; res = new byte[array. length]; i = 0; for (final double x : array) { res[i++] = ((byte) x); return res; ...
byteValue() is a built-in method in Java that returns the value of this Double as a byte(by casting to a byte).
The BitConverter class has a static overloaded GetBytes method that takes an integer, double or other base type value and convert that to a array of bytes. The BitConverter class also have other static methods to reverse this conversion. Some of these methods are ToDouble, ToChart, ToBoolean, ToInt16, and ToSingle.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With