我不知道这是否适用于 Silverlight,但它确实适用于控制台应用程序,并且不需要不安全的代码。
如果您可以将双精度值放入字节数组中,则可以交换字节数组中的字节以更改字节序。这个过程也可以反过来,将字节数组改回双精度数。
下面的代码说明了如何使用 System.InteropServices 在双精度数组和字节数组之间进行转换。Main 方法在控制台中返回两个值:8 和 3.14159。8 表示从 double 中成功创建了一个 8 字节的字节数组,3.14159 表示从字节数组中正确提取了 double。
using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
double d = 3.14159d;
byte[] b = ToByteArray(d);
Console.WriteLine(b.Length);
Console.ReadLine();
double n = FrpmByteArray(b);
Console.WriteLine(n.ToString());
Console.ReadLine();
}
public static byte[] ToByteArray(object anything)
{
int structsize = Marshal.SizeOf(anything);
IntPtr buffer = Marshal.AllocHGlobal(structsize);
Marshal.StructureToPtr(anything, buffer, false);
byte[] streamdatas = new byte[structsize];
Marshal.Copy(buffer, streamdatas, 0, structsize);
Marshal.FreeHGlobal(buffer);
return streamdatas;
}
public static double FromByteArray(byte[] b)
{
GCHandle handle = GCHandle.Alloc(b, GCHandleType.Pinned);
double d = (double)Marshal.PtrToStructure(
handle.AddrOfPinnedObject(),
typeof(double));
handle.Free();
return d;
}
}
}