En mi opinión, debe tener cuidado al hacer esto. La razón por la que uno querría Convertir de BigEndian a LittleEndian es si los bytes que se leen están en BigEndian y el sistema operativo que calcula contra ellos está funcionando en LittleEndian.
C# ya no es un lenguaje de solo ventana. Con puertos como Mono, y también otras plataformas de Microsoft como Windows Phone 7/8, Xbox 360/Xbox One, Windwos CE, Windows 8 Mobile, Linux con MONO, Apple con MONO, etc. Es bastante posible que la plataforma operativa pueda estar en BigEndian, en cuyo caso te enfadarías si convirtieras el código sin hacer ningún control.
El BitConverter ya tiene un campo llamado "IsLittleEndian" que puede usar para determinar si el entorno operativo está en LittleEndian o no. Entonces puedes hacer la reversión condicionalmente.
Como tal, que en realidad sólo escribió algunas [] extensiones de bytes en lugar de hacer una clase grande:
/// <summary>
/// Get's a byte array from a point in a source byte array and reverses the bytes. Note, if the current platform is not in LittleEndian the input array is assumed to be BigEndian and the bytes are not returned in reverse order
/// </summary>
/// <param name="byteArray">The source array to get reversed bytes for</param>
/// <param name="startIndex">The index in the source array at which to begin the reverse</param>
/// <param name="count">The number of bytes to reverse</param>
/// <returns>A new array containing the reversed bytes, or a sub set of the array not reversed.</returns>
public static byte[] ReverseForBigEndian(this byte[] byteArray, int startIndex, int count)
{
if (BitConverter.IsLittleEndian)
return byteArray.Reverse(startIndex, count);
else
return byteArray.SubArray(startIndex, count);
}
public static byte[] Reverse(this byte[] byteArray, int startIndex, int count)
{
byte[] ret = new byte[count];
for (int i = startIndex + (count - 1); i >= startIndex; --i)
{
byte b = byteArray[i];
ret[(startIndex + (count - 1)) - i] = b;
}
return ret;
}
public static byte[] SubArray(this byte[] byteArray, int startIndex, int count)
{
byte[] ret = new byte[count];
for (int i = 0; i < count; ++i)
ret[0] = byteArray[i + startIndex];
return ret;
}
así que imagina este código de ejemplo:
byte[] fontBytes = byte[240000]; //some data loaded in here, E.G. a TTF TrueTypeCollection font file. (which is in BigEndian)
int _ttcVersionMajor = BitConverter.ToUint16(fontBytes.ReverseForBigEndian(4, 2), 0);
//output
_ttcVersionMajor = 1 //TCCHeader is version 1
Skeet escribió uno: http: // www.yoda.arachsys.com/csharp/miscutil/ –
@HansPassant, ¿Sería este uno de esos dlls que requieren que mi código sea de código abierto? ¿Por qué algunos dlls requieren eso? – mowwwalker
Walkerneo borré mi respuesta porque zmbq respondió esencialmente lo mismo 3 minutos antes que yo. El concepto de endianness no se aplica a las matrices de bytes, solo a las palabras, dwords, qwords, etc., que son para grupos de 2, 4, 8 y así sucesivamente. Lo siento si significaría cambiar un montón de código, pero un hombre tiene que hacer lo que un hombre tiene que hacer. –