What type of operators use the logical AND operator (&)?
I need to put in AND a short a
and a "number" m
varying from 1 to 16 and obtain another short b
.
Of that primitive type must be m
?
Example:
? m = ...; //with 1 <= m <= 16
short a = 2;
short b = a & m;
The examples I have seen are like:
short b = a & 0xY;
How can I translate m
value to Y
in such a way that the operation AND is correct?
So b
contains the last m
bits of a
.
If I use m as int, I don't obtain the correct result.
I read this page about Operators but it does not say anything about that.
Thanks.
To get the last m
bits out of a
, you need a bit mask with the least significant m
bits set to 1
and the rest set to 0
.
You can get this by subtracting one from a power of 2 equal to 2m, or 1
shifted left m
times.
int bitmask = (1 << m) - 1;
E.g. if m
is 4
, then 1 << 4
is 16
, minus one is 15
, or 0b1111
, 4 1
s.
Then you can use the bitwise-and operator &
to get a value of b
. But beware, this operator (among others) performs binary numeric promotion. Binary numeric promotion ensures that with differing types that the narrower type is widened to be the same type as the wider type. But it also widens both to int
if they aren't already int
.
This means that both sides are promoted at least to int
before the operation occurs. Cast it back to short
.
short b = (short) (a & bitmask);
Note that because of binary numeric promotion, the type of the bitmask might as well be int
.