Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bitwise operations in if statement

Tags:

c#

bit

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!

like image 391
Kristian Avatar asked Oct 30 '12 12:10

Kristian


People also ask

Can you use bitwise operators on Booleans?

Mixing bitwise and relational operators in the same full expression can be a sign of a logic error in the expression where a logical operator is usually the intended operator.

When would you use bitwise operators?

Examples of uses of bitwise operations include encryption, compression, graphics, communications over ports/sockets, embedded systems programming and finite state machines. A bitwise operator works with the binary representation of a number rather than that number's value.

How do you perform bitwise operations?

The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise AND operator must have integral types.

Is bitwise or faster than logical or?

In general, bitwise operation are always faster then any counterpart but unless what you're doing is the bottle neck of an critical software, I wouldn't recommends using it for no reason other than that one.


1 Answers

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)) { ... }

like image 172
Dave Markle Avatar answered Nov 15 '22 02:11

Dave Markle