I have a binary number and I want to apply a boolean value (true/false) to one of its flags
Supposing a binary value called myBinary I want to apply the boolean value X to the 4th flag (0x08) of myBinary
I know I can do it this way :
function applyBoolean(int myBinary, int mask, boolean X)
{
if (x = true)
myBinary = myBinary | mask
else
myBinary = myBinary & mask
return myBinary
}
EDITED :
So to change the 4th flag I can do so :
applyBoolean(100101, 001000, true) -----> returns : 101101
applyBoolean(100101, 001000, false) -----> returns : 100101
Now I wonder if it's possible to do it without if/else, using only bitwise operations.
Thanks
(I'm assuming
mask == 0x8
ifX == true
andmask == ~0x8
ifX == false
, otherwise your statement wouldn't match your code.)In order to use "only bitwise operations", you would have to convert that boolean into a number.
Since you didn't specify a programming language, I assume you are looking for a general/conceptual answer.
However, whether this is possible or not depends on the features of your programming language, namely on the ability to treat booleans as numbers.
For example, in JavaScript this can be done like
The logic behind this is relatively simple:
0x8
bit to0
(by bitwise AND with the bitwise inverse of0x8
).X
3 bits to the left, implicitly converting it to a number.myBinary
with that value, resulting in bit0x8
being0
forX == false
and1
forX == true
.In PHP, it is practically the same:
In Java, this cannot be done at all using only bitwise operators, as
boolean
cannot be cast to a number. You'd have to useif
, the ternary operator or a function.In some languages, such as Assembly and C prior to C99, this could be considered inapplicable, as those languages lack a (true) boolean type.
If
0
and1
are considered booleans however, the solution is as trivial as rewriting the above snippet in those languages.And last (and probably least too), some languages, such as Brainfuck, simply lack boolean operators, rendering this task impossible.