Mister Epic
Mister Epic

Reputation: 16733

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.

Upvotes: 1

Views: 285

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062865

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;

Upvotes: 6

user2160375
user2160375

Reputation:

Did mean sth like this?

var value = 512 | 1024 | 8192;

var pos = 9;
var isSetNine = (value & (1 << pos)) != 0;

Upvotes: 2

Related Questions