Given n
and m
unsigned integral types, will the expression
(n & m) <= m
always be true ?
Given n
and m
unsigned integral types, will the expression
(n & m) <= m
always be true ?
Yes, it is true.
It should be readily apparent that a necessary condition for y > x
is that at least one bit position is set to 1
in y
but 0
in x
. As &
cannot set a bit to 1
if the corresponding operand bits were not already 1
, the result cannot be larger than the operands.
Yes, it is always true for unsigned integral data types.
Depending on the value of the mask n
, some 1-bits in m
may become 0-bits; all bits that are 0 in m
will remain 0
in the result. From the point of keeping m
as high as possible, the best thing that could happen is that all 1-bits would remain in place, in which case the result would equal m
. In all other cases, the result will be less than m
.
Let m
be m1m2m3m4m5m6m7m8 where mi is a bit.
Now let n
be n1n2n3n4n5n6n7n8.
What would be m & n
? All bits in m
that originally was 0, will stay 0, because 0 & anything
is 0. All bits that were 1, will be 1 only of the corresponding bit in n
is 1.
Meaning that in the "best" case, the number will be the same, but can never get bigger, since not 1's can be created from 0 & anything
.
Let's have an example in order to have a better intuition:
Let m
be 11101011.
What are the numbers that are bigger than m
? 11111111 (trivial), 11111011, 11101111, 11111010, 11111110.
n1n2n3n4n5n6n7n8
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ &
1 1 1 0 1 0 1 1
-----------------------
No way you can get any of the above combinations from doing this.
Yes. To supplement the reasons described in the other answers, a few binary examples make it pretty clear that it will not be possible to make the result greater than either of the args:
0
1
------
0
1
1
------
1
111011
11111
------
11011
111011
111011
------
111011
Given the two arguments, the highest that we can achieve is if both of the arguments are the same value, the result being equal to the value of the two arguments (last example above).
It is impossible to make the result larger no matter what we set the arguments to. If you are able to, then we are in serious trouble. ;)
n & m
has all the bits that are set in m
and in n
.
~n & m
has all the bits that are set in m
but not in n
.
Adding both quantities will give all the bits that are set in m
. That is, m
:
m = (n & m) + (~n & m)
m ≥ (n & m)