1

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.

2
  • 1
    You need to do the bitwise and with 2^9 instead of 9 and compare it to 2^9. Commented Nov 26, 2014 at 14:00
  • 1
    Try using <<, e.g. 2**9 == 1 << 9, 2**13 == 1 << 13 Commented Nov 26, 2014 at 14:00

2 Answers 2

6

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; 
Sign up to request clarification or add additional context in comments.

2 Comments

If you use a Flags enum, you can use the HasFlag method instead of manually "and-ing"
@SebastianNegraszus that is actually not a good idea; HasFlag takes Enum - so it involves boxing.
2

Did mean sth like this?

var value = 512 | 1024 | 8192; var pos = 9; var isSetNine = (value & (1 << pos)) != 0; 

2 Comments

What does the pos variable signify?
@MisterEpic the position on bit (the power of two) that you want to check. It may be 9, 10 or 13 like in your sample.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.