【发布时间】:2018-02-06 15:12:53
【问题描述】:
在我的示例 p 中,我想打包位字段并为此使用单个变量。 我想获得 16 位 PESHeader 结构。但是我不知道如何使用反射来访问和打包这些位。如果您提供比使用反射更好的方法,这将非常有帮助。
我用Bit fields in C#的例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
PESHeader p = new PESHeader();
PES1Header p1 = new PES1Header();
p1.a1 = 3;
p1.a2 = 2;
p1.a3 = 1;
p.b1 = p1;
p.b2.s2 = 1;
long l = PrimitiveConversion.ToLong(p1);
long l2 = PrimitiveConversion.ToLong(p);
for (int i = 63; i >= 0; i--)
{
Console.Write(((l & (1l << i)) > 0) ? "1" : "0");
}
Console.WriteLine();
for (int i = 63; i >= 0; i--)
{
Console.Write(((l2 & (1l << i)) > 0) ? "1" : "0");
}
Console.WriteLine();
}
}
}
[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 PES1Header
{
[BitfieldLength(2)]
public byte a1;
[BitfieldLength(2)]
public byte a2;
[BitfieldLength(4)]
public byte a3;
};
struct PES2Header
{
[BitfieldLength(4)]
public byte s1;
[BitfieldLength(4)]
public byte s2;
};
struct PESHeader
{
public PES1Header b1;
public PES2Header b2;
};
【问题讨论】:
-
你检查BitArray了吗?
-
在我看来,您想重新创建一个预定义的 Header 结构,该结构通常遵循一个非常严格的结构,您是否考虑过使用持有 Enum Flags 的类型并简单地将生成的 Enum-Numbers 连接到二进制形式?
标签: c# bit-manipulation system.reflection bit-fields