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!
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.
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.
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.
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.
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)) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With