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: Code (CSharp): 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: Code (CSharp): 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: https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter?view=net-5.0 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: https://github.com/kurtdekker/datas...ks/Assets/Datasack/Core/DatasackFormatting.cs