Bit Operations Question (easy but my brain can't handle it)

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have multiple Keys enumeration variables (they are, I believe, internally
ints). Let's say I have 3 variables created in C# is follows:

Keys K1 = Keys.S | Keys.Control;
Keys K2 = Keys.S | Keys.Shift | Keys.Control;
Keys K3 = Keys.S | Keys.Shift | Keys.Control | Keys.Alt;

Now, let's say, I want to have a function which, regardless of what Keys
variable I am passed, will return a Keys value WITHOUT any Keys.Control,
Keys.Alt, or Keys.Shift. In other words, for all of the variables above (K1,
K2, K3), the function would simply return Keys.S only. I know that doing this
requires some kind of bit-wise operation but I can't seem to figure it out.

Help?

Alex
 
private Keys myfunction(k As Keys) {
return(k & !(Keys.Control | Keys.Shift | Keys.Alt));
}

I hope the syntax is correct - I come from VB. Anyway, just in case that was
wrong, here's the VB version which you'll need to convert to C# if the above
one is not correct:

Private Function MyFunction(ByVal k As Keys) As Keys
Return (k And Not (Keys.Control Or Keys.Shift Or Keys.Alt))
End Function

hope that helps..
Imran.
 
Imran Koradia said:
private Keys myfunction(k As Keys) {
return(k & !(Keys.Control | Keys.Shift | Keys.Alt));
}

private Keys FilterKeys(Keys k) { return k & ~(Keys.Control | Keys.Shift |
Keys.Alt); }
 
ha! I had the feeling most likely I'd mess up that C# code. Thanks for
pointing that out.
Just out of curiosity - wouldn't the '!' operator work here?

Imran.
 
Imran Koradia said:
ha! I had the feeling most likely I'd mess up that C# code. Thanks for
pointing that out.
Just out of curiosity - wouldn't the '!' operator work here?

No - ! is the boolean "not" operator. ~ is the bitwise compliment
operator.
 
hmm. So I guess VB makes it a bit simpler since both the logical and bitwise
negation operations are done by the 'Not' keyword. Ofcourse, it could get
confusing sometimes as well.

Imran.
 
Back
Top