代码之家  ›  专栏  ›  技术社区  ›  Mike Blandford

Silverlight中的BigEndianBitConverter?

  •  3
  • Mike Blandford  · 技术社区  · 15 年前

    我正在尝试在Silverlight中使用MiscUtil.Conversion实用程序。 http://www.yoda.arachsys.com/csharp/miscutil/

    双字节64位 Int64位双精度

    我打开了反射器,在mscorlib中找到了它们:

    public unsafe long DoubleToInt64Bits(double value)
    {
      return *(((long*)&value));
    }
    
    public unsafe double Int64BitsToDouble(long value)
    {
      return *(((double*) &value));
    }
    

    我如何在Silverlight中执行此操作?

    2 回复  |  直到 15 年前
        2
  •  0
  •   Robert Harvey    15 年前

    我不知道这是否能在Silverlight中工作,但它确实能在控制台应用程序中工作,并且不需要不安全的代码。

    如果可以将双精度值放入字节数组中,则可以交换字节数组中的字节以更改endian值。这个过程也可以颠倒,将字节数组改回双精度数组。

    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;
            }
    
        }
    }