简体   繁体   中英

Type of operand of binary AND operator

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 2 m , or 1 shifted left m times.

int bitmask = (1 << m) - 1;

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

You don't have to 'translate m to Y at all. You just have to evaluate a & m .

If you have a problem when doing that, you have failed to state what it is. You have certainly forgotten to cast the result back to short .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM