Java语言规范中的位移位运算符描述 [英] Bitshift operators description in Java language specification

查看:104
本文介绍了Java语言规范中的位移位运算符描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JLS8中的中指定§JLS-15.19

如果左侧操作数的提升类型为int,则仅将右侧操作数的最低5位用作移位距离.就像右手操作数受到了按位逻辑AND运算符&的约束. (§15.22.1),其掩码值为0x1f(0b11111).因此,实际使用的移动距离始终在0到31(含)范围内.

If the promoted type of the left-hand operand is int, then only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

我不清楚这个粗体陈述.一个例子深表赞赏.

I am not clear about this statement in bold . An example is much appreciated.

推荐答案

这是Java在C和C ++世界中利用编译器优化.对于32位int,使用大于或等于31的移位参数会将正int的结果值设置为0. (对于否定参数,C和C ++中的移位行为是定义的实现.)

It's Java exploiting compiler optimisations from the C and C++ worlds. For a 32 bit int, using an bit-shift argument greater than or equal to 31 will set the resulting value to 0 for a positive int. (For a negative argument the behaviour in C and C++ on shifting is implementation defined).

在C和C ++中,实际上对于32位int使用大于31的值实际上是未定义的行为,而Java联结实际上已明确定义了行为并仅执行了移位参数取模32(这是大多数C和C ++编译器实际上所做的事情).在您引用的JLS代码段中明确提到了此方法.

Whereas in C and C++, actually using a value greater than 31 for a 32 bit int is in fact undefined behaviour, the Java bods have actually defined the behaviour specifically and simply perform the shift with an argument modulo 32 (which is what the majority of C and C++ compilers actually do). This method is mentioned explicitly in the JLS snippet you've quoted.

提取数字的最低5位等效于将该数字取32为模.

Extracting the lowest five order bits of a number is equivalent to taking that number modulo 32.

这篇关于Java语言规范中的位移位运算符描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆