c# endianness binaryreader

C#- Lector binario en Big Endian?



endianness binaryreader (4)

En mi humilde opinión, una respuesta ligeramente mejor, ya que no requiere que se renueve una clase diferente, hace que las llamadas big endian sean obvias y permite que las llamadas big y little-endian se mezclen en la corriente.

public static class Helpers { // Note this MODIFIES THE GIVEN ARRAY then returns a reference to the modified array. public static byte[] Reverse(this byte[] b) { Array.Reverse(b); return b; } public static UInt16 ReadUInt16BE(this BinaryReader binRdr) { return BitConverter.ToUInt16(binRdr.ReadBytesRequired(sizeof(UInt16)).Reverse(), 0); } public static Int16 ReadInt16BE(this BinaryReader binRdr) { return BitConverter.ToInt16(binRdr.ReadBytesRequired(sizeof(Int16)).Reverse(), 0); } public static UInt32 ReadUInt32BE(this BinaryReader binRdr) { return BitConverter.ToUInt32(binRdr.ReadBytesRequired(sizeof(UInt32)).Reverse(), 0); } public static Int32 ReadInt32BE(this BinaryReader binRdr) { return BitConverter.ToInt32(binRdr.ReadBytesRequired(sizeof(Int32)).Reverse(), 0); } public static byte[] ReadBytesRequired(this BinaryReader binRdr, int byteCount) { var result = binRdr.ReadBytes(byteCount); if (result.Length != byteCount) throw new EndOfStreamException(string.Format("{0} bytes required from stream, but only {1} returned.", byteCount, result.Length)); return result; } }

Estoy tratando de mejorar mi comprensión del formato de archivo STFS utilizando un programa para leer todos los diferentes bits de información. Usando un sitio web con una referencia de qué compensaciones contienen qué información, escribí un código que hace que un lector binario recorra el archivo y coloque los valores en las variables correctas.

El problema es que se SUPONE que todos los datos son Big Endian, y todo lo que lee el lector binario es Little Endian. Entonces, ¿cuál es la mejor manera de arreglar esto?

¿Puedo crear una clase mímica de lector binario que devuelva una matriz invertida de bytes? ¿Hay algo que pueda cambiar en la instancia de clase que lo haga leer en big endian para que no tenga que volver a escribir todo?

Cualquier ayuda es apreciada.

edición: intenté agregar Encoding.BigEndianUnicode como un parámetro, pero todavía se lee poco endian.


En mi opinión, debes 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 funciona en LittleEndian.

C # ya no es solo una 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 muy posible que la plataforma operativa esté en BigEndian, en cuyo caso te arruinarías si convirtieras el código sin hacer ninguna verificación.

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 condicional.

Como tal, en realidad escribí algunas extensiones de byte [] en lugar de crear una gran clase:

/// <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


No estoy familiarizado con STFS, pero cambiar de endianess es relativamente fácil. "Orden de red" es big endian, por lo que todo lo que necesita hacer es traducir de la red al orden del host.

Esto es fácil porque ya hay código que hace eso. Mire IPAddress.NetworkToHostOrder , como se explica aquí: ntohs () y ntohl () equivalentes?


No suelo responder a mis propias preguntas, pero he logrado exactamente lo que quería con un código simple:

class BinaryReader2 : BinaryReader { public BinaryReader2(System.IO.Stream stream) : base(stream) { } public override int ReadInt32() { var data = base.ReadBytes(4); Array.Reverse(data); return BitConverter.ToInt32(data, 0); } public Int16 ReadInt16() { var data = base.ReadBytes(2); Array.Reverse(data); return BitConverter.ToInt16(data, 0); } public Int64 ReadInt64() { var data = base.ReadBytes(8); Array.Reverse(data); return BitConverter.ToInt64(data, 0); } public UInt32 ReadUInt32() { var data = base.ReadBytes(4); Array.Reverse(data); return BitConverter.ToUInt32(data, 0); } }

Sabía que eso era lo que quería, pero no sabía cómo escribirlo. Encontré esta página y me ayudó: http://www.codekeep.net/snippets/870c4ab3-419b-4dd2-a950-6d45beaf1295.aspx