BigEndianBitConverter in Silverlight?

I am trying to use the MiscUtil.Conversion utility in Silverlight. http://www.yoda.arachsys.com/csharp/miscutil/

When I try to compile it, I get an error: Silverlight BitConverter class does not have these two methods:

DoubleToInt64Bits Int64BitsToDouble

Ok, I opened Reflector and found them in mscorlib:

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

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

But the problem is that Silverlight does not allow unsafe code. The project properties menu has a blank checkbox next to the "Allow insecure code" caption, but you cannot change the value.

How to do it in Silverlight?

+3
source share
2 answers

, Silverlight , Console .

, , endian-ness. , .

, double byte, System.InteropServices. Main : 8 3.14159. 8 , 8 , 3.14159 , .

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

    }
}
0

Source: https://habr.com/ru/post/1711470/


All Articles