Showing posts with label netmf bitconverter. Show all posts
Showing posts with label netmf bitconverter. Show all posts

Friday, 25 February 2011

Managed BitConverter

So I've been tossing around this BitConverter class that I created for dotCopter, but it wasn't till just last night I found a bug with the ToShort method.

So here is the updated version

namespace DotCopter.Commons.Utilities
{
    public static class BitConverter
    {
        public static void ToBytes(byte[] buffer, int offset, long value)
        {
            Utility.InsertValueIntoArray(buffer, offset, 4, (uint)(value >> 32));
            Utility.InsertValueIntoArray(buffer, offset + 4, 4, (uint)value);
        }
 
        public static unsafe void ToBytes(byte[] buffer, int offset, float value)
        {
            Utility.InsertValueIntoArray(buffer, offset, 4, *((uint*)&value));
        }
 
        public static long ToLong(byte[] buffer, int offset)
        {
            long value = (long)Utility.ExtractValueFromArray(buffer, offset, 4) << 32;
            value |= Utility.ExtractValueFromArray(buffer, offset + 4, 4);
            return value;
        }
 
        public static unsafe float ToFloat(byte[] buffer, int offset)
        {
            uint value = Utility.ExtractValueFromArray(buffer, offset, 4);
            return *((float*)&value);
        }
 
        public static short ToShort(byte[] buffer, int offset)
        {
            return (short)(Utility.ExtractValueFromArray(buffer, offset, 2) >> 16);
        }
 
        public static int ToInt(byte[] buffer, int offset)
        {
            return (int)Utility.ExtractValueFromArray(buffer, offset, 4);
        }
    }
}