日期:2014-05-16  浏览次数:21224 次

c# 共用体 结构体 位段
如题:如何实现位段分配呢? 数据类型怎么实现?
------解决方案--------------------
http://bbs.csdn.net/topics/380102385仅供参考
------解决方案--------------------
个人觉得最好的方法,摘自stackoverflow

using System;

namespace BitfieldTest
{
  [global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
  sealed class BitfieldLengthAttribute : Attribute
  {
    uint length;

    public BitfieldLengthAttribute(uint length)
    {
        this.length = length;
    }

    public uint Length { get { return length; } }
  }

  static class PrimitiveConversion
  {
    public static long ToLong<T>(T t) where T : struct
    {
        long r = 0;
        int offset = 0;

        // For every field suitably attributed with a BitfieldLength
        foreach (System.Reflection.FieldInfo f in t.GetType().GetFields())
        {
            object[] attrs = f.GetCustomAttributes(typeof(BitfieldLengthAttribute), false);
            if (attrs.Length == 1)
            {
                uint fieldLength  = ((BitfieldLengthAttribute)attrs[0]).Length;

                // Calculate a bitmask of the desired length
                long mask = 0;
                for (int i = 0; i < fieldLength; i++)
                    mask 
------解决方案--------------------
= 1 << i;

                r 
------解决方案--------------------
= ((UInt32)f.GetValue(t) & mask) << offset;

                offset += (int)fieldLength;
            }
        }

        return r;
    }
  }

  struct PESHeader
  {
    [BitfieldLength(2)]
    public uint reserved;
    [BitfieldLength(2)]
 &nbs