C# - Binary reader in Big Endian?

后端 未结 6 849
有刺的猬
有刺的猬 2020-12-02 18:38

I\'m trying to improve my understanding of the STFS file format by using a program to read all the different bits of information. Using a website with a reference of which o

6条回答
  •  执笔经年
    2020-12-02 19:23

    IMHO a slightly better answer as it doesn't require a different class to be newed-up, makes the big-endian calls obvious and allows big- and little-endian calls to be mixed in the stream.

    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;
      }
    }
    

提交回复
热议问题