-1

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
  • This is the normal "are all the bits that are set in x also set in y" test.
    – molbdnilo
    Commented Dec 21, 2023 at 13:07
  • "Can anyone simplify this bitwise expression?" - Yes, your friend, the optimizing compiler, can. You usually don't need to worry about stuff like that. The compiler will optimize it for you; just write as readable code as you can and let the compiler worry about micro optimizations like that. Commented Dec 21, 2023 at 14:03

2 Answers 2

5

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

2

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.