问题
和硬件通信时会遇到位操作的问题,比如举例。在C#中我们可以做类似的处理。
实现
按照这种方法即可实现对位操作。具体如下:
public struct MyStruct
{
internal byte raw;
const byte sz0 = 2, loc0 = 0, mask0 = ((1 << sz0) - 1) << loc0;
const byte sz1 = 2, loc1 = loc0 + sz0, mask1 = ((1 << sz1) - 1) << loc1;
const byte sz2 = 1, loc2 = loc1 + sz1, mask2 = ((1 << sz2) - 1) << loc2;
const byte sz3 = 1, loc3 = loc2 + sz2, mask3 = ((1 << sz3) - 1) << loc3;
const byte sz4 = 1, loc4 = loc3 + sz2, mask4 = ((1 << sz4) - 1) << loc4;
const byte sz5 = 1, loc5 = loc4 + sz2, mask5 = ((1 << sz5) - 1) << loc5;
//const int sz6 = 4, loc6 = loc5 + sz2, mask6 = ((1 << sz6) - 1) << loc6;
//const int sz7 = 4, loc7 = loc6 + sz2, mask7 = ((1 << sz7) - 1) << loc7;
public byte Item0
{
get {
return (byte)((raw & mask0) >> loc0); }
set {
raw = (byte)(raw & ~mask0 | (value << loc0) & mask0); }
}