Byte-array to float using bitwise shifting instead of BitConverter

I'm receiving byte-arrays containing float variables (32 bit). In my C# application I'd like to turn byte[] byteArray into a float using bitwise shifting (because it's a lot faster than BitConverter).

Turning a byte-array into a short works like this:

short shortVal = (short)((short)inputBuffer [i++] << 8 | inputBuffer [i++]);

How do I do this for float-variables?

Answers


Let's gut the BCL and use its intestines for our purposes:

    unsafe public static float ToSingle (byte[] value, int startIndex)
    {
        int val = ToInt32(value, startIndex);
        return *(float*)&val;
    }

You can implement ToInt32 using bit shifting.

If you don't need endianness behavior a single unsafe access can give you the float (assuming it's aligned).

Alternatively, you can use a union struct to convert an int to a float.


To get away from C# conventional methods and obtain fast performance, you'll most likely have to implement "unsafe" behavior. You could do something like the C style memory copy.

unsafe public static void MemoryCopy (void* memFrom, void* memTo, int size) {
    byte* pFrom = (byte*)memFrom;
    byte* pTo = (byte*)memTo;
    while (size-- >= 0)
        *pTo++ = *pFrom++;
}

This assumes that the float's endianness is the same going into the byte[] as it on the other end.

To use this you'll have to first fix the byte array since the runtime can move it anytime it wants during garbage collection. Something like this:

float f;

unsafe {
    fixed (byte* ptr = byteArray) {
        MemoryCopy (ptr, &f, sizeof(float));
    }
}

Need Your Help

Using Quickbooks SDK: how should we import commissions?

sdk quickbooks qbfc

One of my developers is attempting to import commissions (related to payroll) from one our products via the QuickBooks SDK.

How to process all data from multiple XML files after merging using XSL

xml xslt

I am using XSL to read in three XML documents which are identical except their attributes have different values (potentially I will be reading many XML files). I want to count the number of times...