Parse bits in a byte to enum - c#

I'm working on a dll that parses binary data I get from a Home Automation module.
But I need some advice on some code I have.
So I get a message with some bytes, and each bit indicates a certain condition in this case.
In the code I have at the moment each condition is an enum, I put the enums in an array and check if the corresponding bit is set.
private void ParseZoneConditionFlag1(int Flag1) // Flag1 = Hex represenation of byte
{
Zone_Status_ZoneConditionFlagEnum[] FlagArray = new Zone_Status_ZoneConditionFlagEnum[8];
FlagArray[0] = Zone_Status_ZoneConditionFlagEnum.Faulted;
FlagArray[1] = Zone_Status_ZoneConditionFlagEnum.Tampered;
FlagArray[2] = Zone_Status_ZoneConditionFlagEnum.Trouble;
FlagArray[3] = Zone_Status_ZoneConditionFlagEnum.Bypassed;
FlagArray[4] = Zone_Status_ZoneConditionFlagEnum.Inhibited;
FlagArray[5] = Zone_Status_ZoneConditionFlagEnum.Low_Battery;
FlagArray[6] = Zone_Status_ZoneConditionFlagEnum.Loss_Supervision;
FlagArray[7] = Zone_Status_ZoneConditionFlagEnum.Reserved;
base.CheckBitsSet(FlagArray, Flag1, ZoneConditionFlags_List);
}
private void ParseZoneConditionFlag2(int Flag2)
{
Zone_Status_ZoneConditionFlagEnum[] FlagArray = new Zone_Status_ZoneConditionFlagEnum[8];
FlagArray[0] = Zone_Status_ZoneConditionFlagEnum.Alarm_Memory;
FlagArray[1] = Zone_Status_ZoneConditionFlagEnum.Bypass_Memory;
FlagArray[2] = Zone_Status_ZoneConditionFlagEnum.Reserved;
FlagArray[3] = Zone_Status_ZoneConditionFlagEnum.Reserved;
FlagArray[4] = Zone_Status_ZoneConditionFlagEnum.Reserved;
FlagArray[5] = Zone_Status_ZoneConditionFlagEnum.Reserved;
FlagArray[6] = Zone_Status_ZoneConditionFlagEnum.Reserved;
FlagArray[7] = Zone_Status_ZoneConditionFlagEnum.Reserved;
base.CheckBitsSet(FlagArray, Flag2, ZoneConditionFlags_List);
}
And the method were I check the actual bits
protected void CheckBitsSet<T>(T[] ConstantArray, int HexValue, List<T> DestinationList)
{
byte b = (byte) HexValue;
for (int i = 0; i < Mask.Length; i++)
{
if(IsBitSet(b, i))
{
DestinationList.Add(ConstantArray[i]);
}
}
}
public bool IsBitSet(byte b, int pos)
{
return (b & (1 << pos)) != 0;
}
This works, but I wonder if there is a cleaner way to do this.
With cleaner I mean without having to add the right enums to an array each time.

How about just:
[Flags]
enum MyFlags : short
{
None = 0,
Faulted = 1 << 0,
Tampered = 1 << 1,
Trouble = 1 << 2,
Bypassed = 1 << 3,
Inhibited = 1 << 4,
LowBattery = 1 << 5,
LossOfSupervision = 1 << 6,
AlarmMemory = 1 << 8,
BypassMemory = 1 << 9
}
static bool IsSet(MyFlags value, MyFlags flag)
{
return ((value & flag) == flag);
}
and read the value as a 2-byte value (short, being careful about endianness), and then cast to MyFlags.
To check for any flag, just:
MyFlags value = ...
bool isAlarmMemory = IsSet(value, MyFlags.AlarmMemory);
It gets tricker when you talk about composite flags, i.e.
bool memoryProblem = IsSet(value, MyFlags.AlarmMemory | MyFlags.BypassMemory);
as you need to figure out whether you mean "is any of these flags set?" vs "are all of these flags set?"
It comes down to the test;
return ((value & flag) == flag); // means "are all set"
return ((value & flag) != 0); // means "is any set"
For reading:
// this is just some garbage that I'm pretending is a message from
// your module; I'm assuming the byte numbers in the image are
// zero-based, so the two that we want are: \/\/\/ (the 6,3)
byte[] data = { 12, 63, 113, 0, 13, 123, 14, 6, 3, 14, 15 };
// and I'm assuming "byte 7" and "byte 8" (image) are zero-based;
// MyFlags uses byte 7 *first*, so it is little-endian; we can get that
// via:
short flagsRaw = (short)(data[7] | (data[8] << 8));
MyFlags flags = (MyFlags)flagsRaw;
// flags has value Tampered | Trouble | AlarmMemory | BypassMemory,
// which is what we expect for {6,3}

Use this:
[Flags]
public enum MyEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
Value5 = 8
}
(...)
void Func(int flag)
{
MyEnum #enum = (MyEnum)flag;
// Testing, whether a flag is set
if ((#enum & MyEnum.Value1) != 0) // sth
}

Related

What is this syntax? var x == ( enum | enum) [duplicate]

For the life of me, I can't remember how to set, delete, toggle or test a bit in a bitfield. Either I'm unsure or I mix them up because I rarely need these. So a "bit-cheat-sheet" would be nice to have.
For example:
flags = flags | FlagsEnum.Bit4; // Set bit 4.
or
if ((flags & FlagsEnum.Bit4)) == FlagsEnum.Bit4) // Is there a less verbose way?
Can you give examples of all the other common operations, preferably in C# syntax using a [Flags] enum?
I did some more work on these extensions - You can find the code here
I wrote some extension methods that extend System.Enum that I use often... I'm not claiming that they are bulletproof, but they have helped... Comments removed...
namespace Enum.Extensions {
public static class EnumerationExtensions {
public static bool Has<T>(this System.Enum type, T value) {
try {
return (((int)(object)type & (int)(object)value) == (int)(object)value);
}
catch {
return false;
}
}
public static bool Is<T>(this System.Enum type, T value) {
try {
return (int)(object)type == (int)(object)value;
}
catch {
return false;
}
}
public static T Add<T>(this System.Enum type, T value) {
try {
return (T)(object)(((int)(object)type | (int)(object)value));
}
catch(Exception ex) {
throw new ArgumentException(
string.Format(
"Could not append value from enumerated type '{0}'.",
typeof(T).Name
), ex);
}
}
public static T Remove<T>(this System.Enum type, T value) {
try {
return (T)(object)(((int)(object)type & ~(int)(object)value));
}
catch (Exception ex) {
throw new ArgumentException(
string.Format(
"Could not remove value from enumerated type '{0}'.",
typeof(T).Name
), ex);
}
}
}
}
Then they are used like the following
SomeType value = SomeType.Grapes;
bool isGrapes = value.Is(SomeType.Grapes); //true
bool hasGrapes = value.Has(SomeType.Grapes); //true
value = value.Add(SomeType.Oranges);
value = value.Add(SomeType.Apples);
value = value.Remove(SomeType.Grapes);
bool hasOranges = value.Has(SomeType.Oranges); //true
bool isApples = value.Is(SomeType.Apples); //false
bool hasGrapes = value.Has(SomeType.Grapes); //false
In .NET 4 you can now write:
flags.HasFlag(FlagsEnum.Bit4)
The idiom is to use the bitwise or-equal operator to set bits:
flags |= 0x04;
To clear a bit, the idiom is to use bitwise and with negation:
flags &= ~0x04;
Sometimes you have an offset that identifies your bit, and then the idiom is to use these combined with left-shift:
flags |= 1 << offset;
flags &= ~(1 << offset);
#Drew
Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:
[Flags]
public enum TestFlags
{
One = 1,
Two = 2,
Three = 4,
Four = 8,
Five = 16,
Six = 32,
Seven = 64,
Eight = 128,
Nine = 256,
Ten = 512
}
class Program
{
static void Main(string[] args)
{
TestFlags f = TestFlags.Five; /* or any other enum */
bool result = false;
Stopwatch s = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
result |= f.HasFlag(TestFlags.Three);
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*
s.Restart();
for (int i = 0; i < 10000000; i++)
{
result |= (f & TestFlags.Three) != 0;
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*
Console.ReadLine();
}
}
Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.
.NET's built-in flag enum operations are unfortunately quite limited. Most of the time users are left with figuring out the bitwise operation logic.
In .NET 4, the method HasFlag was added to Enum which helps simplify user's code but unfortunately there are many problems with it.
HasFlag is not type-safe as it accepts any type of enum value argument, not just the given enum type.
HasFlag is ambiguous as to whether it checks if the value has all or any of the flags provided by the enum value argument. It's all by the way.
HasFlag is rather slow as it requires boxing which causes allocations and thus more garbage collections.
Due in part to .NET's limited support for flag enums I wrote the OSS library Enums.NET which addresses each of these issues and makes dealing with flag enums much easier.
Below are some of the operations it provides along with their equivalent implementations using just the .NET framework.
Combine Flags
.NET flags | otherFlags
Enums.NET flags.CombineFlags(otherFlags)
Remove Flags
.NET flags & ~otherFlags
Enums.NET flags.RemoveFlags(otherFlags)
Common Flags
.NET flags & otherFlags
Enums.NET flags.CommonFlags(otherFlags)
Toggle Flags
.NET flags ^ otherFlags
Enums.NET flags.ToggleFlags(otherFlags)
Has All Flags
.NET (flags & otherFlags) == otherFlags or flags.HasFlag(otherFlags)
Enums.NET flags.HasAllFlags(otherFlags)
Has Any Flags
.NET (flags & otherFlags) != 0
Enums.NET flags.HasAnyFlags(otherFlags)
Get Flags
.NET
Enumerable.Range(0, 64)
.Where(bit => ((flags.GetTypeCode() == TypeCode.UInt64 ? (long)(ulong)flags : Convert.ToInt64(flags)) & (1L << bit)) != 0)
.Select(bit => Enum.ToObject(flags.GetType(), 1L << bit))`
Enums.NET flags.GetFlags()
I'm trying to get these improvements incorporated into .NET Core and maybe eventually the full .NET Framework. You can check out my proposal here.
C++ syntax, assuming bit 0 is LSB, assuming flags is unsigned long:
Check if Set:
flags & (1UL << (bit to test# - 1))
Check if not set:
invert test !(flag & (...))
Set:
flag |= (1UL << (bit to set# - 1))
Clear:
flag &= ~(1UL << (bit to clear# - 1))
Toggle:
flag ^= (1UL << (bit to set# - 1))
For the best performance and zero garbage, use this:
using System;
using T = MyNamespace.MyFlags;
namespace MyNamespace
{
[Flags]
public enum MyFlags
{
None = 0,
Flag1 = 1,
Flag2 = 2
}
static class MyFlagsEx
{
public static bool Has(this T type, T value)
{
return (type & value) == value;
}
public static bool Is(this T type, T value)
{
return type == value;
}
public static T Add(this T type, T value)
{
return type | value;
}
public static T Remove(this T type, T value)
{
return type & ~value;
}
}
}
Bitwise (Flags) enum guide
Old, but wanted to take a stab at a cheat sheet, even if for my own reference:
Operation
Syntax
Example
On
|=
e |= E.A
Off
&= + ~
e &= ~E.A
Toggle
^=
e ^= E.A
Test (.NET API)
.HasFlag
e.HasFlag(E.A)
Test (bitwise)
(see example)
(e & E.A) == E.A
Examples
[Flags]
enum E {
A = 0b1,
B = 0b10,
C = 0b100
}
E e = E.A; // Assign (e = A)
e |= E.B | E.C; // Add (e = A, B, C)
e &= ~E.A & ~E.B; // Remove (e = C) -- alt syntax: &= ~(E.A | E.B)
e ^= E.A | E.C; // Toggle (e = A)
e.HasFlag(E.A); // Test (returns true)
// Testing multiple flags using bit operations:
bool hasAandB = ( e & (E.A | E.B) ) == (E.A | E.B);
Bonus: defining a Flags enum
Typically, we use integers like so:
[Flags]
enum E {
A = 1,
B = 2,
C = 4,
// etc.
But as we approach larger numbers, it's not as easy to calculate the next value:
// ...
W = 4194304,
X = 8388608,
// ..
There are a couple of alternatives, however: binary and hexadecimal literals.
For Binary, just append a 0 at the end of the previous value:
[Flags]
enum E {
A = 0b1,
B = 0b10,
C = 0b100,
// ...
W = 0b100_0000_0000_0000_0000_0000,
X = 0b1000_0000_0000_0000_0000_0000,
Hexadecimal also has a handy pattern and might look a bit less ugly: cycle through 1, 2, 4, 8, adding a zero after each complete iteration.
[Flags]
enum E {
A = 0x1,
B = 0x2,
C = 0x4,
D = 0x8,
E = 0x10, // 16
F = 0x20, // 32, etc.
// ...
W = 0x400000,
X = 0x800000,
To test a bit you would do the following:
(assuming flags is a 32 bit number)
Test Bit:
if((flags & 0x08) == 0x08) (If bit 4 is set then its true)
Toggle Back (1 - 0 or 0 - 1): flags = flags ^ 0x08;
Reset Bit 4 to Zero: flags = flags & 0xFFFFFF7F;
This was inspired by using Sets as indexers in Delphi, way back when:
/// Example of using a Boolean indexed property
/// to manipulate a [Flags] enum:
public class BindingFlagsIndexer
{
BindingFlags flags = BindingFlags.Default;
public BindingFlagsIndexer()
{
}
public BindingFlagsIndexer( BindingFlags value )
{
this.flags = value;
}
public bool this[BindingFlags index]
{
get
{
return (this.flags & index) == index;
}
set( bool value )
{
if( value )
this.flags |= index;
else
this.flags &= ~index;
}
}
public BindingFlags Value
{
get
{
return flags;
}
set( BindingFlags value )
{
this.flags = value;
}
}
public static implicit operator BindingFlags( BindingFlagsIndexer src )
{
return src != null ? src.Value : BindingFlags.Default;
}
public static implicit operator BindingFlagsIndexer( BindingFlags src )
{
return new BindingFlagsIndexer( src );
}
}
public static class Class1
{
public static void Example()
{
BindingFlagsIndexer myFlags = new BindingFlagsIndexer();
// Sets the flag(s) passed as the indexer:
myFlags[BindingFlags.ExactBinding] = true;
// Indexer can specify multiple flags at once:
myFlags[BindingFlags.Instance | BindingFlags.Static] = true;
// Get boolean indicating if specified flag(s) are set:
bool flatten = myFlags[BindingFlags.FlattenHierarchy];
// use | to test if multiple flags are set:
bool isProtected = ! myFlags[BindingFlags.Public | BindingFlags.NonPublic];
}
}
C++ operations are: & | ^ ~ (for and, or, xor and not bitwise operations). Also of interest are >> and <<, which are bitshift operations.
So, to test for a bit being set in a flag, you would use:
if (flags & 8) //tests bit 4 has been set

Bit manipulation of Uint32 bitfields in C#

I have two enums in C#
public class PlayerAttributes
{
private UInt32 m_AttributeFlagsMask;
private UInt32 m_AttributeFlagsBitmap;
[Flags]
public enum EAttributesFlagsBmp
{
AIn = 0,
BIn = (1 << 1), //1
CIn = (1 << 2), //2
DIn = (1 << 3), //4
EIn = (1 << 4), //8
FIn = (1 << 5), //16
GIn = (1 << 6) //32
}
[Flags]
public enum EAttributeFlagsMask
{
None = 0,
AIn = (1 << 1), //1
BIn = (1 << 2), //2
CIn = (1 << 3), //4
DIn = (1 << 4), //8
EIn = (1 << 5), //16
FIn = (1 << 6) //32
}
public UInt32 AttributeFlagsMask { get { return m_AttributeFlagsMask; } private set { m_AttributeFlagsMask = value; } }
public UInt32 AttributeFlagsBmp { get { return m_AttributeFlagsBmp; } private set { m_AttributeFlagsBmp = value; } }
public bool SetAInAndBIn(bool a_in, bool b_in)
{
if(a_in && !b_in)
{
UInt32 flag = ((UInt32)PlayerAttributes.EAttributesFlagsBmp.AIn | ~(UInt32)PlayerAttributes.EAttributesFlagsBmp.BIn);
}else if(bin && !a_in)
{
UInt32 flag = (~(UInt32)PlayerAttributes.EAttributesFlagsBmp.AIn | (UInt32)PlayerAttributes.EAttributesFlagsBmp.BIn);
}
AttributeFlagsBmp = flag
return true;
}
}
The above code doesn't seem to set the value correctly.
What I want is in
case 1 AIn should be set and BIn should be unset. (All other bits should be unchanged)
and
In case 2 BIn should be set and AIn should be unset. (All other bits should be unchanged)
how do I achieve this
Not sure if that is what you want, but if the following line
((UInt32)PlayerAttributes.EAttributesFlagsBmp.AIn | ~(UInt32)PlayerAttributes.EAttributesFlagsBmp.BIn)
is expected to set A and unset B, while not changing the others, it will not work (it will actually flip all the others). To set A and unset B without changing anything else, you should use:
((UInt32)PlayerAttributes.EAttributesFlagsBmp.AIn & ~(UInt32)PlayerAttributes.EAttributesFlagsBmp.BIn)
Just like in regular booleans, when negating one side you need to change Or to And (and vice-versa) in the comparison to keep the same behavior.
EDIT:
The reason why the others flags gets erased when you set is because you are setting only those 2 flags on a property and then overwriting whatever exists on the property, by setting the value on it. In order to just change the values that is already on the property, you must use the appropriate operator on its values and then set it back. Like this:
AttributeFlagsBitmap = AttributeFlagsBitmap |
(UInt32)PlayerAttributes.EAttributesFlagsBmp.AIn &
~(UInt32)PlayerAttributes.EAttributesFlagsBmp.BIn;

Mapping an enum T's values to valid flag values (0, 1, 2, 4, 8, 16, 24...)

Lets say I have the following enum:
public enum SomeEnum
{
A, // = 0
B, // = 1
C, // = 2
D, // = 3
E, // = 4
...
}
Basically, what I want to do is to map every value to valid mask value (0, 1, 2, 4, 8, 16, 32, 64, 128...), so that SomeEnum.A would be equivalent to 0, while SomeEnum.B to 1, SomeEnum.C to 2, SomeEnum.D to 4, SomeEnum.E to 8 and so on. I kinda got it working, but I'm facing another problem: the more values the given enum has, the bigger gets that mapping, probably resulting in a super ultra giant long long long long number.
Are there any known techniques for this?
Here is my code:
public class Flagger<T> where T : struct
{
private static Dictionary<int, ulong> dictionary = new Dictionary<int, ulong>();
static Flagger()
{
int indexer = 0;
// Since values can be duplicated, we use names instead
foreach (String name in Enum.GetNames(typeof(T)))
{
ulong value = 1UL << indexer++; // 0, 1, 2, 4, 8, 16...
Console.WriteLine("{0} generated value {1}", name, value);
dictionary.Add(name.GetHashCode(), value);
}
}
private ulong flags;
public void Add(T value)
{
// Create hash only once for both checkup and storation
int hash = value.ToString().GetHashCode();
if (Check(hash))
{
ulong flag = dictionary[hash];
flags &= flag;
}
}
public void Remove(T value)
{
// Create hash only once for both checkup and storation
int hash = value.ToString().GetHashCode();
if (Check(hash))
{
ulong flag = dictionary[hash];
flags &= ~flag;
}
}
/// <summary>
/// Tests whether a value has already been added or not
/// </summary>
public bool Check(T value)
{
int hash = value.ToString().GetHashCode();
return Check(hash);
}
/// <summary>
/// Quick checkup because no hash needs to be computed
/// </summary>
private bool Check(int hash)
{
if (dictionary.ContainsKey(hash))
{
ulong flag = dictionary[hash];
return (flags & flag) == flag;
}
return false;
}
}
The reason for all this is that I'm working with the System.Window.Input.Key enum and I'm not able to test whether some flags are enabled, for example:
using System.Windows.Input;
int vk = 0x55; // U
Key key = KeyInterop.KeyFromVirtualKey(vk);
if ((Key.W & key) == key)
{
Console.WriteLine("True!");
}
The above "if" condition returns me true, which is not really true!
Use bit shifting:
[Flags]
public enum MyEnum
{
None = 0,
First = 1 << 0,
Second = 1 << 1,
Third = 1 << 2,
Fourth = 1 << 3
}
EDIT: after clarification of the problem, this is how you'd go about evaluating if a flagged key enum value contains the equivalent value of a differently-typed, but similarly-named enum value.
[Flags]
public enum Keys1
{
O = 0,
K = 1,
A = 1 << 1,
Y = 1 << 2
}
public enum Keys2
{
O,
K,
A,
Y
}
public bool DoesIncludeKey(Keys1 keys1, Keys2 keys2)
{
var keys1Names = keys1.ToString().Split(',');
return keys1Names.Contains(keys2.ToString());
}
//ToString() on keysVals results in "O,K",
//which is what makes the above function work.
var keysVals = Keys1.O | Keys1.K;
//true!
var includesK = DoesIncludeKey(keysVals, Keys2.K);
//false.
var includesA = DoesIncludeKey(keysVals, Keys2.A);

Determining values in a bitmask

I have a protocol guide for a piece of hardware where I can extract 16 different kinds of data. To indicate I want all data, I would enter 65535 as the mask.
2^0 (1)
+ 2^1 (2)
+ 2^2 (4)
...
+ 2^15 (32768)
==============
65535
I now need to indicate I need options 9, 10, and 13. Presumably I simply need to use the following calculation:
2^9 (512)
+ 2^10 (1024)
+ 2^13 (8192)
==============
9728
(If I'm off-base here, or there is a programmatic way to do this, I'd be interested to know!)
What I would like to know is how I would in future extract all the numbers that were involved in the summation.
I had thought I would be able to check with (9728 & 9) == 9, (9728 & 10) == 10, and (9728 & 13) == 13, but all those return false.
bit 9 is 256; bit 10 is 512; bit 13 is 4096.
So:
if((val & 256) != 0) { /* bit 9 is set */ }
if((val & 512) != 0) { /* bit 10 is set */ }
if((val & 4096) != 0) { /* bit 13 is set */ }
You could also use an enum for convenience:
[Flags]
public enum MyFlags {
None = 0,
Foo = 1,
Bar = 2,
...
SomeFlag = 256,
AnotherFlag = 512,
...
}
then:
MyFlags flags = (MyFlags)val;
if((flags & MyFlags.SomeFlag) != 0) {/* SomeFlag is set */}
And likewise:
MyFlags thingsWeWant = MyFlags.Foo | MyFlags.SomeFlag | MyFlags.AnotherFlag;
int val = (int)thingsWeWant;
Did mean sth like this?
var value = 512 | 1024 | 8192;
var pos = 9;
var isSetNine = (value & (1 << pos)) != 0;

How to get two (0~15) numbers as properties with one byte as backing field?

I'm making a tile based 2d platformer and every byte of memory is precious. I have one byte field that can hold values from 0 to 255, but what I need is two properties with values 0~15. How can I turn one byte field into two properties like that?
do you mean just use the lower 4 bits for one value and the upper 4 bits for the other?
to get two values from 1 byte use...
a = byte & 15;
b = byte / 16;
setting is just the reverse as
byte = a | b * 16;
Using the shift operator is better but the compiler optimizers usually do this for you nowadays.
byte = a | (b << 4);
To piggy back off of sradforth's answer, and to answer your question about properties:
private byte _myByte;
public byte LowerHalf
{
get
{
return (byte)(_myByte & 15);
}
set
{
_myByte = (byte)(value | UpperHalf * 16);
}
}
public byte UpperHalf
{
get
{
return (byte)(_myByte / 16);
}
set
{
_myByte = (byte)(LowerHalf | value * 16);
}
}
Below are some properties and some backing store, I've tried to write them in a way that makes the logic easy to follow.
private byte HiAndLo = 0;
private const byte LoMask = 15; // 00001111
private const byte HiMask = 240; // 11110000
public byte Lo
{
get
{
// ----&&&&
return (byte)(this.hiAndLo & LoMask);
}
set
{
if (value > LoMask) //
{
// Values over 15 are too high.
throw new OverflowException();
}
// &&&&0000
// 0000----
// ||||||||
this.hiAndLo = (byte)((this.hiAndLo & HiMask) | value);
}
}
public byte Hi
{
get
{
// &&&&XXXX >> 0000&&&&
return (byte)((this.hiAndLo & HiMask) >> 4);
}
set
{
if (value > LoMask)
{
// Values over 15 are too high.
throw new OverflowException();
}
// -------- << ----0000
// XXXX&&&&
// ||||||||
this.hiAndLo = (byte)((hiAndLo & LoMask) | (value << 4 ));
}
}

Categories

Resources