Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply/remove bitmask depending on condition

Tags:

c

bitmask

I would like to simplify the following expression (block is an integer, either 0 or 1):

if (block)
    opts = opts & ~O_NONBLOCK;
else
    opts = opts | O_NONBLOCK;

This is what I've come up with:

opts = block ? opts & ~O_NONBLOCK : opts | O_NONBLOCK;

I'm sure, however, that there's a much clever way to do that.

like image 867
watain Avatar asked Sep 02 '26 00:09

watain


1 Answers

How about this?

opts = (opts & ~O_NONBLOCK) | (!block * O_NONBLOCK);

I do prefer the explicitness of your first option over this somewhat cryptic solution, though.

like image 93
Thomas Avatar answered Sep 04 '26 23:09

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!