using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Runtime.InteropServices;
using
System.Text;
namespace
Common
{
public
class ConvertData
{
/// <summary>
/// 构造函数
/// </summary>
public
ConvertData()
{
}
/// <summary>
/// 将byte[]数组转换为double[]数组
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
public
double [] BytesToDoubles( byte [] b)
{
// Initialize unmanged memory to hold the array.
int
size = Marshal.SizeOf(b[0]) * b.Length;
IntPtr pnt = Marshal.AllocHGlobal(size);
try
{
// Copy the array to unmanaged memory.
Marshal.Copy(b, 0, pnt, b.Length);
// Copy the unmanaged array back to another managed array.
double [] managedArray2 = new
double [b.Length / 8];
Marshal.Copy(pnt, managedArray2, 0, b.Length / 8);
return
managedArray2;
}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
}
}
/// <summary>
/// 获取内存中double[],并转换为String字符串
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
public
string DoublesToString( double [] doubleArray)
{
string
values = "" ;
for
( int
i = 0; i < doubleArray.Length; i++)
{
values += doubleArray[i] + "," ;
}
return
values;
}
/// <summary>
/// 获取内存中double[],并转换为String字符串
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
public
string BytesToString( byte [] b)
{
double [] doubleArray = BytesToDoubles(b);
return
DoublesToString(doubleArray);
}
/// <summary>
/// 获取内存中double[],并转换为String字符串
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
public
string GetByteToDouble( byte [] b)
{
// Initialize unmanged memory to hold the array.
int
size = Marshal.SizeOf(b[0]) * b.Length;
IntPtr pnt = Marshal.AllocHGlobal(size);
string
values = "" ;
try
{
// Copy the array to unmanaged memory.
Marshal.Copy(b, 0, pnt, b.Length);
// Copy the unmanaged array back to another managed array.
double [] managedArray2 = new
double [b.Length / 8];
Marshal.Copy(pnt, managedArray2, 0, b.Length / 8);
for
( int
i = 0; i < managedArray2.Length; i++)
{
values += managedArray2[i] + "," ;
}
}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
}
return
values;
}
/// <summary>
/// 将double[]数组转换为byte[]数组
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public
byte [] DoublesToBytes( double [] d)
{
int
size = Marshal.SizeOf(d[0]) * d.Length;
IntPtr pnt = Marshal.AllocHGlobal(size);
try
{
// Copy the array to unmanaged memory.
Marshal.Copy(d, 0, pnt, d.Length);
// Copy the unmanaged array back to another managed array.
byte [] managedArray2 = new
byte [d.Length * 8];
Marshal.Copy(pnt, managedArray2, 0, d.Length * 8);
return
managedArray2;
}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
}
}
}
}
|