Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operation result and booleans

Tags:

c++

c

The code that frustrates me is as follows:

bool a = 0x00000FF0 & 0x00000FF0 == 0x00000FF0;
if (a) {
  Serial.println("True");
} else {
  Serial.println("False");
}

This prints "False". I really can't understand why. Some more tests:

bool a = 0x00000FF0 & 0x00000FF0 == 0x00000FF0;
Serial.println(a);

prints 0.

And:

unsigned long a = 0x00000FF0 & 0x00000FF0;
Serial.println(a, HEX);

prints FF0.

like image 675
Rustam Avatar asked Nov 14 '14 17:11

Rustam


People also ask

Do bitwise operators work with 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.

What is the difference between bitwise operations and boolean logic operations?

The key difference between Bitwise and Logical operators is that Bitwise operators work on bits and perform bit by bit operations while logical operators are used to make a decision based on multiple conditions.

Which number represents false in Bitwise operation?

A little bit more into explaining how shift works with a boolean. So true as you said will be 1 and false will be 0.

What are the different boolean and bitwise operators in Java?

First, logical operators work on boolean expressions and return boolean values (either true or false), whereas bitwise operators work on binary digits of integer values (long, int, short, char, and byte) and return an integer.


1 Answers

Operator precedence, compile with warnings:

warning: suggest parentheses around comparison in operand of ‘&’ [-Wparentheses]

Change to

bool a = (0x00000FF0 & 0x00000FF0) == 0x00000FF0;
like image 68
David Ranieri Avatar answered Sep 29 '22 20:09

David Ranieri