justyy
justyy

Reputation: 6041

how to make these two comparisons into 1 (bit logics)

input three integers, n, tag and flag.

if flag = 0 then

return ((n & tag) == tag);

if flag != 0 then

return ((n & tag) != tag);

Ideally, I want something simple without if statement.

Upvotes: 0

Views: 50

Answers (2)

xtu
xtu

Reputation: 417

If flag can be converted to a bool, it can be simplified to:

return !(flag ^ ((n & tag) == tag))

Upvotes: 1

qwr
qwr

Reputation: 10974

You could convert the flag to a bool. In C++:

 bool b_flag = flag;
 return !b_flag * ((n & tag) == tag) + b_flag * ((n & tag) != tag);

Or you could use a ternary operator.

Upvotes: 1

Related Questions