Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit masking (javascript): how to check ALL flags

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?

like image 430
pistacchio Avatar asked Oct 08 '15 13:10

pistacchio


1 Answers

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.)

like image 135
Pointy Avatar answered Sep 29 '22 06:09

Pointy