帮助在C#中的位字段 [英] help for bit field in c#

查看:109
本文介绍了帮助在C#中的位字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c中有位字段定义,使用它可以节省内存.

There is bit field definition in c , using it may save memory.
such as

struct{
   unit32 aa:3;
   unit32 bb:12;
   unit32 cc:15;
   unit32 :2;//reserved
}my bit field;



结构我的位字段"仅占用内存中的32位;
我的问题是,如何在c#中执行此操作,非常感谢.



struct "my bit field" only takes up 32bit in memory;
my question is how can we do this in c#,thanks a lot.

推荐答案

您需要查看

您.Net中不能做位字段.您将不得不寻找另一种方式来表示此信息.例如,使用属性:

You cannot do bit fields in .Net. You will have to find another way to represent this information. For example, using properties:

struct MyBitField {
 private uint data;

 public byte aa { get { return data & 0x03; } set { data = (data & ~ 0x03) | (value & 0x03); } }
 public ushort bb { get { return (data >> 3) & 0x0FFF; } set { data = (data & ~ 0x00007FFC) | ((value & 0x0FFF) << 3; } }
 public ushort bb { get { return (data >> 15) & 0x0FFF; } set { data = (data & ~ 0x3FFF8000) | ((value & 0x0FFF) << 15; } }
}



如果您不需要复制原始位字段的打包并可以扩展它,那就更好了:



It''s much better if you don''t need to replicate the packing of the original bit field and can expand it:

struct MyNotBitFieldAnyMore {
 public byte aa;
 public ushort bb, cc;
}


这篇关于帮助在C#中的位字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆