在C#中实现BigEndian的数字
时间:2011-01-23 来源:天方
由于C#的struct不支持继承,以及C#的泛型不像C++那样支持类似类似template C<int i>的非类型模板参数,导致这个没法写成一个泛型的结构,只能先定义一个公共方法类,提供基础功能函数,并对每个类型实现一个struct(好在就几种类型的数字)。
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的现成方法了。以后有需要再弄好了。