有人能解释一下为什么我不能用这种方式将两个字节相乘吗?
byte a = 1;
byte b = 1;
byte c = a*b;
或
byte a = 1;
byte b = 1;
short c = a*b;
为什么我必须这样做?
byte a = 1;
byte b = 1;
byte c = (byte)(a*b);
或
byte a = 1;
byte b = 1;
int/double/float/long c = a*b;
最佳答案
当使用byte
执行数学运算时,二进制数字提升 会发生,如JLS, Section 5.6.2 所指定的那样.
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:
If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted to float.
Otherwise, if either operand is of type long, the other is converted to long.
Otherwise, both operands are converted to type int.
(强调我的)
这会强制您分配给至少与 int
一样宽的类型,或者转换回 byte
。
关于java - 两个字节相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30174855/