|
Public URL
|
http://www.coderprofile.com/pinned-code/207/bitwise-boolean-inverse |
|
|
Language
|
C
|
|
Expires
|
Never
|
|
Length
|
36 Characters (3 Lines)
|
|
Password
|
no password
|
|
|
|
Inverse a boolean value using bitwise &
bool b = false; b = ((b + 1) & 1)
|
|
| Please login to post comments. |
|
|
I don't know, lol. Didn't really care when I wrote it. Thanks for the tip though!
|
|
|
In that case, why didn't you just do:
b = ~b & 1
?
The complement operation is faster than an addition.
|
|
|
Incorrect. False is 0, and True is 1. The nature of a boolean is that it only has 2 possible values.
What you are getting into is the evaluation of a value as a boolean. In almost all programming languages, you are correct. 0 evaluates to False, and anything but will evaluate to True. However, this does not make True equal to anything but False.
My code is perfectly acceptable (though unreasonable to use an production code).
|
|
|
This is incorrect and should not be used in applications as it is exploitable.
The correct code would be:
bool bvar = false;
bvar = !bvar; // bvar is now true
bvar = !bvar; // bvar is now false etc...
The reason being is that with boolean values, false is 0 and true is ANYTHING else (not always 1).
|
|
 |
Craige Leeder (20) Canada, Ontario |
|
|
Craige has 5 fans
become a fan |
|
 |
|
|
 |
|