Search Unity

optimizing binary reading

Discussion in 'Scripting' started by pretender, Apr 30, 2021.

  1. pretender

    pretender

    Joined:
    Mar 6, 2010
    Posts:
    839
    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):
    1. byte[] vectorBuffer = new byte[2 * 3];
    2.             buf.Read(vectorBuffer, 0, 6);
    3.             var x = (ushort)(vectorBuffer[0] | vectorBuffer[1] << 8);
    4.  
    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):
    1.  
    2.         Vector3 b;
    3.         //b.x = buffer.ReadSingle();
    4.         //b.y = buffer.ReadSingle();
    5.  
    6.         b.x = (float)(boundingBox[0] | boundingBox[1] << 8 | boundingBox[2] << 16 | boundingBox[3] << 24);
    7.         b.y = (float)(boundingBox[4] | boundingBox[5] << 8 | boundingBox[6] << 16 | boundingBox[7] << 24);
    8.  
    What am I doing wrong, how to take endianes into account?
    thanks!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    18,986
unityunity