简体   繁体   English

二进制AND运算符的操作数类型

[英]Type of operand of binary AND operator

What type of operators use the logical AND operator (&)? 哪种类型的运算符使用逻辑AND运算符(&)? I need to put in AND a short a and a "number" m varying from 1 to 16 and obtain another short b . 我需要输入AND缩写a和一个介于1到16之间的“数字” m并获得另一个short b Of that primitive type must be m ? 该原始类型必须为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? 如何以与AND正确的方式将m值转换为Y So b contains the last m bits of a . 所以b包含最后m的位a

If I use m as int, I don't obtain the correct result. 如果将m用作int,则不会获得正确的结果。

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 . 为了得到最后的m位出a ,你需要用最少的显著位掩码m设置位1 ,其余设置为0

You can get this by subtracting one from a power of 2 equal to 2 m , or 1 shifted left m times. 您可以通过从等于2 m的2的幂中减去1或向左移位1次获得m

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

Eg if m is 4 , then 1 << 4 is 16 , minus one is 15 , or 0b1111 , 4 1 s. 例如,如果m4 ,则1 << 416 ,负1为15 ,或0b1111 1 s。

Then you can use the bitwise-and operator & to get a value of b . 然后,您可以使用按位与运算符&来获得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 . 但是,这也拓宽了既int ,如果他们不已经int

This means that both sides are promoted at least to int before the operation occurs. 这意味着在操作发生之前,双方至少都提升为int Cast it back to short . 把它抛short

short b = (short) (a & bitmask);

Note that because of binary numeric promotion, the type of the bitmask might as well be int . 注意,由于二进制数字提升,位掩码的类型也可能是int

You don't have to 'translate m to Y at all. 您完全不需要将m转换为Y You just have to evaluate a & m . 您只需要评估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 . 您当然已经忘记将结果short

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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