gpt4 book ai didi

java ->> [Java] 的原始提升

转载 作者:搜寻专家 更新时间:2023-10-31 20:09:39 26 4
gpt4 key购买 nike

我在下一个代码片段中遇到了对原始提升的误解。

byte a = 2;
int b = a >> 4L;

我会期待什么?

long b = (int)a >> 4L;
long b = a >> 4L;
int b = a >> 4L;

int >> long 将提升为更大的数据类型 (long),并且不会使用结果 int 类型进行编译。

我收到了什么?

它编译得很好。 为什么?

最佳答案

JLS 不会在这里“提升为更大的数据类型”,因为它不会为移位运算符执行二进制数字提升。这包含在 JLS, Section 15.19 中。 .

Unary numeric promotion (§5.6.1) is performed on each operand separately. (Binary numeric promotion (§5.6.2) is not performed on the operands.)

一元数字提升将字节 a 提升为 int。字面量 4L 没有变化,但无论如何它只需要是一个整型。

It is a compile-time error if the type of each of the operands of a shift operator, after unary numeric promotion, is not a primitive integral type.

然后对于移位,仅使用最低 5 位有效位来移位 int

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.

运算符的结果是 int,而不是 long,因此可以将其分配给 int 而不会出现编译器错误。

The type of the shift expression is the promoted type of the left-hand operand.

关于java ->> [Java] 的原始提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36559370/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com