Search code examples
c++bit-manipulationbitwise-operators

Can anyone simplify this bitwise expression?


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


Solution

  • !(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.