Set a given binary flag

450 views Asked by At

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

1

There are 1 answers

0
Siguza On

(I'm assuming mask == 0x8 if X == true and mask == ~0x8 if X == 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

function applyBoolean(myBinary, X)
{
    return (myBinary & ~0x8) ^ (X << 3);
}

The logic behind this is relatively simple:

  • Set 0x8 bit to 0 (by bitwise AND with the bitwise inverse of 0x8).
  • Shift X 3 bits to the left, implicitly converting it to a number.
  • XOR myBinary with that value, resulting in bit 0x8 being 0 for X == false and 1 for X == true.

In PHP, it is practically the same:

function applyBoolean($myBinary, $X)
{
    return ($myBinary & ~0x8) ^ ($X << 3);
}

In Java, this cannot be done at all using only bitwise operators, as boolean cannot be cast to a number. You'd have to use if, 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 and 1 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.