获得大端二进制读取器的三种方法是什么?

时间:2016-04-29 02:19:54

标签: c# .net

我想要几种不同的方法来解决我对大端二进制读取器的需求。

1 个答案:

答案 0 :(得分:0)

第一种方法是子类BinaryReader

public class BigEndianBinaryReader : BinaryReader
    {
        public BigEndianBinaryReader(Stream input) : base(input)
        {
        }
        public BigEndianBinaryReader(Stream input, Encoding encoding) : base(input, encoding)
        {
        }
        public BigEndianBinaryReader(Stream input, Encoding encoding, bool leaveOpen) : base(input, encoding, leaveOpen)
        {
        }
        public override UInt16 ReadUInt16()
        {
            return (UInt16)IPAddress.NetworkToHostOrder(base.ReadInt16());
        }
        public override UInt32 ReadUInt32()
        {
            return (UInt32)IPAddress.NetworkToHostOrder(base.ReadInt32());
        }
        public override UInt64 ReadUInt64()
        {
            return (UInt64)IPAddress.NetworkToHostOrder(base.ReadInt64());
        }
        public override Int16 ReadInt16()
        {
            return (Int16)IPAddress.NetworkToHostOrder(base.ReadInt16());
        }
        public override Int32 ReadInt32()
        {
            return (Int32)IPAddress.NetworkToHostOrder(base.ReadInt32());
        }
        public override Int64 ReadInt64()
        {
            return (Int64)IPAddress.NetworkToHostOrder(base.ReadInt64());
        }
    }

第二种方法是实现一些扩展方法

 static class BinaryReaderExtensionMethods
    {
        static public UInt16 ReadUInt16BE(this BinaryReader br)
        {
            return (UInt16)IPAddress.NetworkToHostOrder(br.ReadInt16());
        }
        static public UInt32 ReadUInt32BE(this BinaryReader br)
        {
            return (UInt32)IPAddress.NetworkToHostOrder(br.ReadInt32());
        }
        static public UInt64 ReadUInt64BE(this BinaryReader br)
        {
            return (UInt64)IPAddress.NetworkToHostOrder(br.ReadInt64());
        }
        static public Int16 ReadInt16BE(this BinaryReader br)
        {
            return (Int16)IPAddress.NetworkToHostOrder(br.ReadInt16());
        }
        static public Int32 ReadInt32BE(this BinaryReader br)
        {
            return (Int32)IPAddress.NetworkToHostOrder(br.ReadInt32());
        }
        static public Int64 ReadInt64BE(this BinaryReader br)
        {
            return (Int64)IPAddress.NetworkToHostOrder(br.ReadInt64());
        }
    }

第三种方法(也许是最好的!)是使用Jon Skeet的精彩图书馆,其中也包括作家。 link here