optimizing binary reading

Hi guys,
I was playing a bit with optimizations, and since I have custom binary format I wanted to optimized it.
I have managed to replace a lot of buffer.ReadUInt16() with bit shifting, it’s slightly faster like this:

byte[] vectorBuffer = new byte[2 * 3];
            buf.Read(vectorBuffer, 0, 6);
            var x = (ushort)(vectorBuffer[0] | vectorBuffer[1] << 8);

I want to further optimized but couldn’t manage to get the same thing for 4 byte values like floats, I know it has something to do with endianes but couldn’t swap bits the way it would produce correct values. I have something like this:

        Vector3 b;
        //b.x = buffer.ReadSingle();
        //b.y = buffer.ReadSingle();

        b.x = (float)(boundingBox[0] | boundingBox[1] << 8 | boundingBox[2] << 16 | boundingBox[3] << 24);
        b.y = (float)(boundingBox[4] | boundingBox[5] << 8 | boundingBox[6] << 16 | boundingBox[7] << 24);

What am I doing wrong, how to take endianes into account?
thanks!

This is the magic sauce you’re looking for, to turn a float into a simple 32-bit “integer-ish” quantity, which you can then bit-flick into your bytes:

And obviously it works the other way too: four bytes back into a float.

I use it for losslessly storing floats in my Datasacks module: