Skip to content

Concern about endianness byte ordering in UnsafeBlitFormatter #1868

Description

@codetaylor

It is my understanding that architecture endianness does not affect the ordering of arrays or the ordering of fields in structs.

My concern is that the following code ...

            // Reverse the byte order if necessary.
            if (isLittleEndian != BitConverter.IsLittleEndian)
            {
                for (int i = 0, j = resultAsBytes.Length - 1; i < j; i++, j--)
                {
                    byte tmp = resultAsBytes[i];
                    resultAsBytes[i] = resultAsBytes[j];
                    resultAsBytes[j] = tmp;
                }
            }

... located here ...

... is intended to reverse byte order to handle endianness, but will also:

  • if the array elements are a built-in value type, reverse the order of the array,
  • if the array elements are structs with fields of the same size, reverse the array and struct field ordering, or
  • if the array elements are structs with fields of different sizes, reverse the array and corrupt the field values.

Please correct me if I misunderstand.

Would something like this be more appropriate for reversing the byte order of each element while retaining its position in the array and struct field order?

            int blockCount = resultAsBytes.Length / blockSize;
            for (int block = 0; block < blockCount; block++)
            {
                int pos = block * blockSize;
                for (int i = pos, j = pos + blockSize - 1; i < j; i++, j--)
                {
                    byte temp = resultAsBytes[i];
                    resultAsBytes[i] = resultAsBytes[j];
                    resultAsBytes[j] = temp;
                }
            }

Where blockSize is the byte size of each built-in value type in the array or equivalent sized struct fields, ie. 4 for both float and Vector2.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions