Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negate a boolean based on another boolean

What's the short, elegant, bitwise way to write the last line of this C# code without writing b twice:

bool getAsIs = ....
bool b = ....

getAsIs ? b : !b
like image 492
HappyNomad Avatar asked Dec 21 '12 01:12

HappyNomad


People also ask

How do you negate a boolean?

Use the not operator to negate a boolean value The not keyword returns the logical negation of a boolean value. Invoke the not keyword by placing it in front of a boolean expression. If an expression evaluates to True , placing not in front of it will return False , and vice-versa.

How do you invert a boolean?

Invert a boolean method or propertyPress Ctrl+Shift+R and then choose Invert Boolean.

How do you find the opposite of a boolean in Python?

Python's not operator allows you to invert the truth value of Boolean expressions and objects. You can use this operator in Boolean contexts, such as if statements and while loops.

How do you negate a boolean in Javascript?

The logical NOT ( ! ) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true ; otherwise, returns true .


2 Answers

The truth table can be expressed as:

getAsIs    b    getAsIs ? b : !b
--------------------------------
0          0    1
0          1    0
1          0    0
1          1    1

The result can be expressed as:

result = (getAsIs == b);
like image 134
drf Avatar answered Nov 04 '22 08:11

drf


Try using binary XOR (^ Operator (C# Reference)):

bool getAsIs = true;
bool b = false;

bool result = !(getAsIs ^ b);
like image 28
horgh Avatar answered Nov 04 '22 09:11

horgh