在C#中实现BigEndian的数字

在我们的PC机中,C#的数字是LittleEndian的,导致在做网络协议和和文件解析时有许多不便,因此,我写了个BigEndian的数字的类,这里记录一下,以后还会经常用到。

    static class BigEndianUIntHelper
    {
        public static uint ToUInt32(byte[] data)
        {
            Contract.Assume(data.Length <= 4);
            return BitConverter.ToUInt32(new byte[4 - data.Length].Concat(data).Reverse().ToArray(), 0);
        }

        public static byte[] ToBytes(uint num, int size)
        {
            Contract.Assume(size <= 4);
            return BitConverter.GetBytes(num).Take(size).Reverse().ToArray();
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    struct BigEndianUInt24
    {
        const int size = 3;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = size)]
        byte[] data;

        public static implicit operator uint(BigEndianUInt24 d) { return BigEndianUIntHelper.ToUInt32(d.data); }
        public static implicit operator BigEndianUInt24(uint d) { return new BigEndianUInt24() { data = BigEndianUIntHelper.ToBytes(d, size) }; }
        public override string ToString() { return ((uint)this).ToString(); }
    }

    [StructLayout(LayoutKind.Sequential)]
    struct BigEndianUInt32
    {
        const int size = 4;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = size)]
        byte[] data;

        public static implicit operator uint(BigEndianUInt32 d) { return BigEndianUIntHelper.ToUInt32(d.data); }
        public static implicit operator BigEndianUInt32(uint d) { return new BigEndianUInt32 { data = BigEndianUIntHelper.ToBytes(d, size) }; }
        public override string ToString() { return ((uint)this).ToString(); }
    }

其实这里BigEndianUIntHelper的两个函数应该优化一下的,这里为了图简单,就直接用BitConverter的现成方法了。以后有需要再弄好了。

相关文章:在C#中实现类似位域的操作 

你可能感兴趣的:(C#)