Kristian
Kristian

Reputation: 1388

Using bitwise operations in if statement

Can someone explain why is this not valid? I get "can't convert to int to bool"

 if (b & 1)

also, why can't I do

 b & 1 

in code, is this the correct way of doing this?

 int b = b & 1
 if(b)

Thanks!

Upvotes: 6

Views: 7989

Answers (1)

Dave Markle
Dave Markle

Reputation: 97821

It's because the result of b & 1 is an integer (if b is an integer).

A correct way to do this is (among others):

if ((b & 1) != 0) { ... }

or

if (Convert.ToBoolean(b & 1)) { ... }

Upvotes: 13

Related Questions