栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

C#中的位字段

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#中的位字段

我可能会使用属性将某些东西组合在一起,然后是一个转换类,以将适当地归属的结构转换为位域基元。就像是…

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)]        public uint scrambling_control;        [BitfieldLength(1)]        public uint priority;        [BitfieldLength(1)]        public uint data_alignment_indicator;        [BitfieldLength(1)]        public uint copyright;        [BitfieldLength(1)]        public uint original_or_copy;    };    public class MainClass    {        public static void Main(string[] args)        { PESHeader p = new PESHeader(); p.reserved = 3; p.scrambling_control = 2; p.data_alignment_indicator = 1; long l = PrimitiveConversion.ToLong(p); for (int i = 63; i >= 0; i--) {     Console.Write( ((l & (1l << i)) > 0) ? "1" : "0"); } Console.WriteLine(); return;        }    }}

产生预期的…
000101011。当然,它需要更多的错误检查和更合理的键入,但是(我认为)该概念是合理的,可重用的,并且使您可以轻松地将十几个结构进行维护。

亚当



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/506810.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号