8

If I have the number '00001000' and the mask '00101000', how can i check, with a binary operation, if both the bits in the number are set? number & mask return true if at least one bit match, but I need to check for all of them to match. How to?

Salman A
  • 262,204
  • 82
  • 430
  • 521
pistacchio
  • 56,889
  • 107
  • 278
  • 420

1 Answers1

13

Just compare to the mask:

if ((number & mask) === mask) {
  // all bits are set!
}

The only way the result of the & operation will be exactly the same as the value of the mask is when the number has all the bits set. (The test number may have more bits set; if you want to check to see if it's got exactly the same bits set and unset, then that's a simple equality test.)

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    I guess you have to put parenthesis around `(number & mask)` otherwise the equality test is performed in the first place – webdeb Sep 10 '20 at 21:13
  • Other ways include `(flags | mask) == flags`, or `((~flags) & mask) == 0)`. But yeah `(flags & mask) == mask` is the standard idiom. https://godbolt.org/z/8P79sz4h3 shows how C compilers handle it, with clang transforming to `((~flags) & mask) == 0)` on some ISAs where that's more efficient. AArch64 allows a different encoding for immediates to bitwise boolean instructions, allowing repeated bit-patterns. In Javascript this is all up to the JIT, but same difference. – Peter Cordes Jun 08 '22 at 20:13