java - 两个字节相乘

标签 java byte

有人能解释一下为什么我不能用这种方式将两个字节相乘吗?

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:

  1. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

  2. 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/

相关文章:

c# - 如何在 c#.net 中将结构转换为字节数组,但结构大小仅在运行时定义

java - 如何使用相同类型的对象创建对象

java - 使用主线程或单独线程在后台播放音频文件的正确方法/方法

java - 查找单词中非重复字母的所有排列

java.lang.ClassNotFoundException : Class org. apache.hadoop.hdfs.DistributedFileSystem

c++ - 给定一个整数N> 0,区间[0,2 ^ N)中有多少个整数恰好有N-1个设置位?编写返回正确答案的简短函数

java - 在 JavaFX 中使用多个选择框来过滤 ListView

dart - 使用 Dart 获取 double 的 4 个字节

java - 如何在 python 中将字节数组转换为 double ?

c - C 字节读取器中的段错误(核心转储)