Can anyone simplify this bitwise expression?

134 Views Asked by At

Working on an ECS implementation in C++ and I have an itch that this expression can be simplified but I'm honestly not confident enough with bitwise operations to figure it out:

(x & y) == x

If you have any tips on simplifying bitwise expressions that'd be great thanks

Edit: Formatting

2

There are 2 best solutions below

0
Jakob Stark On BEST ANSWER

!(x & ~y) will get you the same result. However, I leave it to the reader, if this is a 'simplified' version. If you have a decent c++ compiler, consider not wasting your time with this kind of stuff. The compiler will figure out the most efficient machine code anyway. Readable code should be the main goal.

As an example, here you can see live, that a well known compiler (clang in this case) will compile both (x & y) == x and !(x & ~y) into the same code.

0
mksteve On

I don't think it can,

expr = x & y;

gives the common bits of the 2 values.

expr == x

tests if the common bits cover exactly x.