“可能的精度损失” Java 是疯了还是我错过了什么?
我收到了“精度损失”错误,而实际上应该没有,AFAIK。
这是一个实例变量:
byte move=0;
这发生在此类的方法中:
this.move=(this.move<<4)|(byte)(Guy.moven.indexOf("left")&0xF);
移动是一个字节,移动仍然是一个字节,其余的被转换为一个字节。
我收到此错误:
[javac] /Users/looris/Sviluppo/dumdedum/client/src/net/looris/android/toutry/Guy.java:245: possible loss of precision
[javac] found : int
[javac] required: byte
[javac] this.move=(this.move<<4)|(byte)(Guy.moven.indexOf("left")&0xF);
[javac] ^
我尝试了很多变体,但仍然收到相同的错误。
我现在已经毫无头绪了。
I'm getting a "loss of precision" error when there should be none, AFAIK.
this is an instance variable:
byte move=0;
this happens in a method of this class:
this.move=(this.move<<4)|(byte)(Guy.moven.indexOf("left")&0xF);
move is a byte, move is still a byte, and the rest is being cast to a byte.
I get this error:
[javac] /Users/looris/Sviluppo/dumdedum/client/src/net/looris/android/toutry/Guy.java:245: possible loss of precision
[javac] found : int
[javac] required: byte
[javac] this.move=(this.move<<4)|(byte)(Guy.moven.indexOf("left")&0xF);
[javac] ^
I've tried many variations but I still get the same error.
I'm now clueless.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,所有逻辑运算符 (& | ^) 都会返回 int,无论其操作数如何。您还必须转换 x|y 的最终结果。
Actually all logic operatos (& | ^) return an int, regardless of their operands. You have to cast the final result of x|y as well.
这是因为
this.move<<4
返回一个 int。当 Java 找到 移位运算符 它适用 一元促销 到每个操作数;在这种情况下,两个操作数都会提升为
int
,结果也是如此。其他 Java 运算符的行为类似;请参阅相关且具有指导性的讨论,“可能导致精度损失的不同行为”。
That's because
this.move<<4
returns an int.When Java finds a shift operator it applies unary promotion to each operand; in this case, both operands are promoted to
int
, and so is the result.The behaviour is similar for other Java operators; see a related and instructive discussion, "Varying behavior for possible loss of precision".
按位或操作数受二进制数字提升的影响。以下是其在 JLS 中的定义,
如您所见,没有字节类型,因此默认情况下所有字节都提升为 int。你必须将其转换回字节才能消除警告,
The bitwise OR operands are subject to Binary Numeric Promotion. Here is how its' defined in JLS,
As you can see, there is no byte type so all the bytes are promoted to int by default. You have to cast it back to byte to get rid of the warning,