Chin Chin - 3 months ago 10
Java Question

How to determine if all set bits in one number is also set in another number?

Given 2 binary strings

a
and
b
of the same length (e.g.
111000
and
110000
), is it possible to check if all set bits in
b
is also set in
a
using bitwise operations? In the above example,
b = 110000
has two set bits in position 1 and 2 (from left to right), and those bits are also set in
a = 111000
.

I can compare two strings character-wise but that would be too slow. I know I can turn the strings into number with something like
Integer.parseInt(a, 2);
but I don't know the bitwise operations to use to achieve the task.

Answer

Mask the bits and then check if they're still all set.

int a = 0b111000;
int b = 0b110000;

if ((a & b) == b) {
    ...
}